nginx反向代理配置去除字首
阿新 • • 發佈:2020-08-27
使用nginx做反向代理的時候,可以簡單的直接把請求原封不動的轉發給下一個服務。設定proxy_pass請求只會替換域名,如果要根據不同的url字尾來訪問不同的服務,則需要通過如下方法:
方法一:
1 server { 2 listen 8000; 3 server_name abc.com; 4 access_log "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1G" main; 5 6 location ^~/user/ {7 proxy_set_header Host $host; 8 proxy_set_header X-Real-IP $remote_addr; 9 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 10 proxy_set_header X-NginX-Proxy true; 11 12 proxy_pass http://user/; 13 } 14 15 location ^~/order/ { 16 proxy_set_header Host $host;17 proxy_set_header X-Real-IP $remote_addr; 18 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 19 proxy_set_header X-NginX-Proxy true; 20 21 proxy_pass http://order/; 22 } 23 }
^~/user/
表示匹配字首是user
的請求,proxy_pass
的結尾有/
, 則會把/user/*
後面的路徑直接拼接到後面,即移除user
。
方法二:
upstream user { server localhost:8089 weight=5; } upstream order { server localhost:8090 weight=5; } server { listen 80; server_name abc.com; access_log "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1G" main; location ^~/user/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; rewrite ^/user/(.*)$ /$1 break; proxy_pass http://user; } location ^~/order/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; rewrite ^/order/(.*)$ /$1 break; proxy_pass http://order; } }
proxy_pass
結尾沒有/
,rewrite
重寫了url。
以上摘自csdn-gong-cy,僅供自己學習使用