天天看點

Nginx:位址重寫(return和rewrite)

Nginx的重寫指令用于改變用戶端的URL請求。主要有

return

rewrite

。兩個指令都有重寫URL的能力,但

rewrite

支援更複雜的功能。

Return指令

server

中傳回 301 重定向:

server {
        listen 80;
        server_name www.olddomain.com;
        return 301 $scheme://www.newdomain.com$request_uri;
}
           

location

location = /tutorial/learning-nginx {
     return 301 $scheme://example.com/nginx/understanding-nginx
}
           

Rewrite指令

文法介紹

rewrite regex replacement-url [flag];
           
  • regex: 正規表達式
  • replacement-url: 替換的URL
  • flag: 用于進行一些額外的處理

不同flag的效果:

flag 說明
last 停止解析,并開始搜尋與更改後的

URI

相比對的

location

;
break 中止 rewrite,不再繼續比對
redirect 傳回臨時重定向的 HTTP 狀态 302
permanent 傳回永久重定向的 HTTP 狀态 301

注意:

rewrite

隻能傳回301和302狀态碼,如果需要傳回其他狀态碼,可以在

rewrite

指令後使用

return

案例

簡單案例

https://example.com/nginx-tutorial

重寫為

https://example.com/somePage.html

location = /nginx-tutorial 
{ 
    rewrite ^/nginx-tutorial?$ /somePage.html last; 
}
           
動态替換案例

https://www.example.com/user.php?id=11

https://exampleshop.com/user/11

location = /user.php 
{ 
    rewrite ^/user.php?id=([0-9]+)$ /user/$1 last; 
}
           

其中

$1

表示

regex

中第一個括号中的值,第二個括号中的值可通過

$2

擷取

手機通路重定向網址

https://www.example.com

https://m.exampleshop.com

location = /
{
    if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
    rewrite ^(.*) https://m.example.com$1 redirect;
    }
}
           

繼續閱讀