轉:NGINX中的proxy_pass和rewrite
阿新 • • 發佈:2018-03-12
http狀態碼 gin cep itl def rem 參數 nta bre
章作者:luxianghao
文章來源:http://www.cnblogs.com/luxianghao/p/6807081.html 轉載請註明,謝謝合作。
免責聲明:文章內容僅代表個人觀點,如有不當,歡迎指正。
---
rewrite
syntax: rewrite regex replacement [flag] Default: — Context: server, location, if
- 如果正則表達式(regex)匹配到了請求的URI(request URI),這個URI會被後面的replacement替換
- rewrite的定向會根據他們在配置文件中出現的順序依次執行
- 通過使用flag
- 如果replacement以“http://”, “https://”, or “$scheme”開頭,處理將會終止,請求結果會以重定向的形式返回給客戶端(client)
- 如果replacement字符串裏有新的request參數,那麽之前的參數會附加到其後面,如果要避免這種情況,那就在replacement字符串後面加上“?”,eg:
rewrite ^/users/(.*)$ /show?user=$1? last;=
- 如果正則表達式(regex)裏包含“}” or “;”字符,需要用單引號或者雙引號把正則表達式引起來
- last
- 結束當前的請求處理,用替換後的URI重新匹配location;
- 可理解為重寫(rewrite)後,發起了一個新請求,進入server模塊,匹配location;
- 如果重新匹配循環的次數超過10次,nginx會返回500錯誤;
- 返回302 http狀態碼 ;
- 瀏覽器地址欄顯示重地向後的url
- break
- 結束當前的請求處理,使用當前資源,不在執行location裏余下的語句;
- 返回302 http狀態碼 ;
- 瀏覽器地址欄顯示重地向後的url
- redirect
- 臨時跳轉,返回302 http狀態碼;
- 瀏覽器地址欄顯示重地向後的url
- permanent
- 永久跳轉,返回301 http狀態碼;
- 瀏覽器地址欄顯示重定向後的url
proxy_pass
Syntax: proxy_pass URL; Default: — Context: location, if in location, limit_except
- 不影響瀏覽器地址欄的url
- 設置被代理server的協議和地址,URI可選(可以有,也可以沒有)
- 協議可以為http或https
- 地址可以為域名或者IP,端口可選;eg:
proxy_pass http://localhost:8000/uri/;
- 如果一個域名可以解析到多個地址,那麽這些地址會被輪流使用,此外,還可以把一個地址指定為 server group(如:nginx的upstream), eg:
upstream backend { server backend1.example.com weight=5; server backend2.example.com:8080; server unix:/tmp/backend3; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; } server { location / { proxy_pass http://backend; } }
- server name, port, URI支持變量的形式,eg:
proxy_pass http://$host$uri;
- 如果proxy_pass的URL定向裏包括URI,那麽請求中匹配到location中URI的部分會被proxy_pass後面URL中的URI替換,eg:
location /name/ { proxy_pass http://127.0.0.1/remote/; } 請求http://127.0.0.1/name/test.html 會被代理到http://example.com/remote/test.html
- 如果proxy_pass的URL定向裏不包括URI,那麽請求中的URI會保持原樣傳送給後端server,eg:
location /name/ { proxy_pass http://127.0.0.1; } 請求http://127.0.0.1/name/test.html 會被代理到http://127.0.0.1/name/test.html
- 一些情況下,不能確定替換的URI
- location裏是正則表達式,這種情況下,proxy_pass裏最好不要有URI
- 在proxy_pass前面用了rewrite,如下,這種情況下,proxy_pass是無效的,eg:
location /name/ { rewrite /name/([^/]+) /users?name=$1 break; proxy_pass http://127.0.0.1; }
轉:NGINX中的proxy_pass和rewrite