文章作者: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 “;”字符,需要用單引號或者雙引號把正則表達式引起來
可選的
flag參數如下:
- 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;
這種情況下,nginx會在server groups(upstream后端server)里搜索server name,如果沒有找到,會用dns解析,
請求的URI會按照下面的規則傳給后端服務,下面結合具體的例子來說明URI的傳遞規則,假設nginx中server部分的配置如下:
server { listen 80; server_name example.com; proxy_read_timeout 120; proxy_send_timeout 120; include /etc/nginx/fastcgi_params; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; location / { ... } }
- 如果proxy_pass的URL定向里包括URI,那么請求中匹配到location中URI的部分會被proxy_pass后面URL中的URI替換,eg:
location /name/ { proxy_pass http://127.0.0.1/remote/; } 請求http://example.com/name/test.html 會被代理到http://127.0.0.1/remote/test.html
- 如果proxy_pass的URL定向里不包括URI,那么請求中的URI會保持原樣傳送給后端server,eg:
location /name/ { proxy_pass http://127.0.0.1; } 請求http://example/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; }