地址重寫可以達到目的:
縮短URL,隱藏實際路徑提高安全性
易於用戶記憶和鍵入
易於被搜索引擎收錄
常見網站應用場景:
1. 網站文件移動或文件目錄名稱改變,出於SEO需要,你需要保持舊的URL
規則:
rewrite regex replacement flag
- flag : break, last, redirect, permanent
last : 停止當前這個請求,並根據rewrite匹配的規則重新發起一個請求。新請求又從第一個階段執行。。。
break: 相對last, break並不會重新發起一個請求,只是跳過當前的rewrite階段,並執行本請求後續的執行階段
redirect :302臨時重定向,地址欄改變,爬蟲不更新URI
permanent: 301永久重定向,地址欄改變,爬蟲更新URI
下面重點說下 last 和 break 的區別,並做個小實驗
編輯/usr/local/nginx/conf/nginx.conf
location /break/ {
rewrite ^/break/(.*) /test/$1 break;
return 402;
}
location /last/ {
rewrite ^/last/(.*) /test/$1 last;
return 403;
}
location /test/ {
return 508;
}
請求 tpl01.liang.com/break/break.html
返回 404; //如果存在 /test/break.html頁面則 返回200
請求 tpl01.liang.com/last/last.html
返回 508 //不管存不存在 /test/last.html 都是返回508
原因分析: break 與last都停止後續rewrite指令集,不同之處在於last會重新發起新的請求並重新匹配location, 而break不會
rewrite regex replacement flag
正則表達式匹配模式如下:
區分大小寫匹配: ~
不分區大小寫匹配: ~*
區分大小寫不匹配: !~
不區分大小寫不匹配: !~*
匹配模式如下:
-判斷文件是否存在: -f
-判斷目錄是否存在:-d
-判斷文件是否可執行: -x
-判斷文件,目錄,連接是否存在: -e
應用案例
例子一: *.jpg或*.gif --> logo.png
location /{
root html;
index index.html index.htm;
rewrite \.(gif|jpg)$ /logo.png;
}
例子二:域名跳轉
tpl01.liang.com --> tpl02.liang.com
server {
listen 80;
server_name tpl01.liang.com;
location /{
root html;
index index.html index.htm;
rewrite ^/ http://tpl02.liang.com/;
}
}
例子三: 根據瀏覽器返回不同的頁面
server {
listen 80;
server_name tpl01.liang.com
location /{
root html;
index.html index.htm;
if($http_user_agent ~MSIE){
rewrite ^(.*)$ /nginx-ie/$1 break;
}
}
}
例子四: 訪問資源不存在時,重定向到指定頁面
if(!-e $request_filename){
rewrite ^/ http://tpl01.liang.com/none.html;
}