Nginx反向代理設(shè)置
文章轉(zhuǎn)自:
https://xuexb.github.io/learn-nginx/example/proxy_pass.html
Nginx反向代理設(shè)置
proxy_pass 搞定反向代理,對于接口代理、負(fù)載均衡很是實(shí)用,但 proxy_pass 指令后面的參數(shù)很有講究。url 只是 host
$uri ,如:?http://host - √?https://host - √?http://host:port - √?https://host:port - √?http://host/ - x?http://host:port/ - x
location 匹配的完整路徑將直接透傳給 url ,如:// 訪問:/ 后端:/// 訪問:/api/xx 后端:/api/xx// 訪問:/api/xx?aa 后端:/api/xx?aalocation / {proxy_pass http://node:8080;}// 訪問:/api/ 后端:/api/// 訪問:/api/xx 后端:/api/xx// 訪問:/api/xx?aa 后端:/api/xx?aa// 訪問:/api-xx?aa 后端:location /api/ {proxy_pass http://node:8080;}// 訪問:/api/ 后端:/api/// 訪問:/api/xx 后端:/api/xx// 訪問:/api/xx?aa 后端:/api/xx?aa// 訪問:/api-xx?aa 后端:/api-xx?aalocation /api {proxy_pass http://node:8080;}
url 包含路徑
/ 也是存在的,如:?http://host - x?https//host/ - √?http://host:port - x?https://host:port/ - √?http://host/api - √?http://host/api/ - √
proxy_pass url 的 url 包含路徑時(shí),匹配時(shí)會根據(jù) location 的匹配后的鏈接透傳給 url ,注意匹配后就是這樣:location 規(guī)則 | 訪問的原始鏈接 | 匹配之后的路徑 |
location / | / | |
location / | /a | a |
location / | /a/b/c?d | a/b/c?d |
location /a/ | /a/ | |
location /a/ | /a/b/c?d | b/c?d |
proxy_pass url 包含路徑時(shí),將會把匹配之后的路徑透傳給 url ,如:// 訪問:/ 后端:/// 訪問:/api/xx 后端:/api/xx// 訪問:/api/xx?aa 后端:/api/xx?aalocation / {proxy_pass http://node:8080/;}// 訪問:/api/ 后端:/// 訪問:/api/xx 后端:/xx// 訪問:/api/xx?aa 后端:/xx?aa// 訪問:/api-xx?aa 未匹配location /api/ {proxy_pass http://node:8080/;}// 訪問:/api 后端:/// 訪問:/api/ 后端://// 訪問:/api/xx 后端://xx// 訪問:/api/xx?aa 后端://xx?aa// 訪問:/api-xx?aa 后端:/-xx?aalocation /api {proxy_pass http://node:8080/;}// 訪問:/api/ 后端:/v1// 訪問:/api/xx 后端:/v1xx// 訪問:/api/xx?aa 后端:/v1xx// 訪問:/api-xx?aa 未匹配location /api/ {proxy_pass http://node:8080/v1;}// 訪問:/api/ 后端:/v1/// 訪問:/api/xx 后端:/v1/xx// 訪問:/api/xx?aa 后端:/v1/xx// 訪問:/api-xx?aa 未匹配location /api/ {proxy_pass http://node:8080/v1/;}
proxy_pass url 中包含路徑時(shí),結(jié)尾的 / 最好同 location 匹配規(guī)則一致。當(dāng) proxy_pass 遇到正則
location 以正則形式匹配時(shí),proxy_pass 就不能以 / 結(jié)束了,也就是不能包含路徑了,比如錯(cuò)誤的:location ~* ^/api/ {proxy_pass http://host/;}location / {if ($uri ~* ^/api/) {proxy_pass http://host/;}}
重寫代理鏈接 - url rewrite
location ~* ^/api/ {rewrite ^/api/(.*) /?path=$1 break;proxy_pass http://node:8080;}
/api/的鏈接重寫為 /?path= 的鏈接透傳給 node:8080 服務(wù),有意思的是當(dāng)使用 rewrite 指令并且生效后,proxy_pass url 鏈接中的路徑會被忽略,如:// 訪問:/ 后端:/node/// 訪問:/api 后端:/node/api// 訪問:/api/ 后端:/?path=// 訪問:/api/a/b/c 后端:/?path=a/b/clocation / {rewrite ^/api/(.*) /?path=$1 break;proxy_pass http://node:8080/node/;}
歡迎關(guān)注我的公眾號“須彌零一”,更多技術(shù)文章第一時(shí)間推送。
評論
圖片
表情
