1、rewrite語法:
指令語法:rewrite regex replacement[flag];
默認值:none
應用位置:server、location、if
rewrite是實現URL重定向的重要指令,他根據regex(正則表達式)來匹配內容跳轉到replacement,結尾是flag標記
簡單的小例子:
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
平滑重啟:
[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)