1. 程式人生 > 其它 >Nginx的rewrite(地址重定向)剖析

Nginx的rewrite(地址重定向)剖析

Nginx的rewrite(地址重定向)剖析

1、rewrite語法:

  指令語法:rewrite regex replacement[flag];

  預設值:none

  應用位置:server、location、if

  rewrite是實現URL重定向的重要指令,他根據regex(正則表示式)來匹配內容跳轉到replacement,結尾是flag標記

  簡單的小例子:

?
1 rewrite ^/(.*) http://www.baidu.com/ permanent; # 匹配成功後跳轉到百度,執行永久301跳轉

  常用正則表示式:

字元 描述
\ 將後面接著的字元標記為一個特殊字元或者一個原義字元或一個向後引用
^ 匹配輸入字串的起始位置
$ 匹配輸入字串的結束位置
* 匹配前面的字元零次或者多次
+ 匹配前面字串一次或者多次
? 匹配前面字串的零次或者一次
. 匹配除“\n”之外的所有單個字元
(pattern) 匹配括號內的pattern

  rewrite 最後一項flag引數:

標記符號 說明
last 本條規則匹配完成後繼續向下匹配新的location URI規則
break 本條規則匹配完成後終止,不在匹配任何規則
redirect 返回302臨時重定向
permanent 返回301永久重定向

2、應用場景:

  • 調整使用者瀏覽的URL,看起來規範
  • 為了讓搜尋引擎收錄網站內容,讓使用者體驗更好
  • 網站更換新域名後
  • 根據特殊的變數、目錄、客戶端資訊進行跳轉

3、常用301跳轉:

  之前我們通過用起別名的方式做到了不同地址訪問同一個虛擬主機的資源,現在我們可以用一個更好的方式做到這一點,那就是跳轉的方法

  還是用www.brian.com虛擬主機為例子,修改配置檔案brian.conf:

[root@Nginx www_date]# cat brian.conf 
    server {                          # 添加個server區塊做跳轉
    listen     
80; server_name brian.com; rewrite ^/(.*) http://www.brian.com/$1 permanent; } server { listen 80; server_name www.brian.com; location / { root html/brian; index index.html index.htm; } access_log logs/brian.log main gzip buffer=128k flush=5s; error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }

  檢查語法:

[root@Nginx conf]# 
[root@Nginx conf]# ../sbin/nginx -t
nginx: the configuration file /opt/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx//conf/nginx.conf test is successful

  平滑重啟:

?
1 [root@Nginx conf]# ../sbin/nginx -s reload

  windows測試效果:

4、域名跳轉:

  我們不僅可以做相同虛擬主機的資源域名跳轉,也能做不同虛擬主機的域名跳轉,我們下面就跳轉下當訪問brian.com域名的時候跳轉到www.baidu.com的頁面:

  修改www.brian.com虛擬主機的brian.conf配置檔案:

[root@Nginx www_date]# cat brian.conf 
    server {
        listen       80;
        server_name  brian.com;
        location / {
            root   html/brian;
            index  index.html index.htm;
        }
    if ( $http_host ~* "^(.*)") {
        set $domain $1;
        rewrite ^(.*) http://www.baidu.com break;
    }
        access_log logs/brian.log main gzip buffer=128k flush=5s; 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 }

  windows測試:(訪問brian.com 跳轉到了www.baidu.com)