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
Nginx配置proxy_pass轉發的/路徑問題
在nginx中配置proxy_pass時,如果是按照^~匹配路徑時,要注意proxy_pass后的url最后的/,當加上了/,相當於是絕對根路徑,則nginx不會把location中匹配的路徑部分代理走;如果沒有/,則會把匹配的路徑部分也給代理走。
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com/;
}
如上面的配置,如果請求的url是http://servername/static_js/test.html
會被代理成http://js.test.com/test.html
而如果這么配置
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://js.test.com;
}
則會被代理到http://js.test.com/static_js/test.htm
當然,我們可以用如下的rewrite來實現/的功能
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
rewrite /static_js/(.+)$ /$1 break;
proxy_pass http://js.test.com;
}
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; }