Nginx:地址重寫(return和rewrite)


Nginx的重寫指令用於改變客戶端的URL請求。主要有returnrewrite。兩個指令都有重寫URL的能力,但rewrite支持更復雜的功能。

Return指令

server中返回 301 重定向:

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

location中返回 301 重定向:

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;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM