rewrite重定向 這些規則可以寫在server裏面,也可以寫在location裏面相當的靈活。
所用位置:
server {
listen 80;
server_name www.maomaochong.com ;
root /root;
index index.html index.htm;
location / {
rewrite ^/(.*)$ /erp/ permanent;
proxy_pass http://ERP/erp/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
也可以這樣:
location ~ .*\.
(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|doc|ppt|pdf|xls|swf|zip|ipa|apk)$
{
if ( $request_uri ~ /jsp/(.*)$ )
{
proxy_pass http://www.maomaochong.com/jsp/$1;
}
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
root /var/www/webfile/; #網站靜態文件放置目錄
expires 7d;
}
說明一下location靜態文件配置這個地方! 因爲我的靜態文件放在了nginx服務器上,所以靜態文件是直接調用本地得。但是唯獨www.maomaochong.com/jsp/ 這個目錄下的靜態文件放在後端(另一臺服務器上)。每次我訪問www.maomaochong.com/jsp/這個地址,他調用的每次都是在/var/www/webfile/這個目錄下尋找(優先調用本地,本地沒有就直接報錯)。所以肯定是訪問不到的。所以我在這裏寫了一個 $request_uri 的if判斷。判斷請求的路徑是否是/jsp/ 如果是,就交給後端處理。這這樣就避免了訪問jsp這個目錄調用本地靜態文件的問題。
rewrite符號的含義:
.*: 標示所有
^:以xx開頭
$: 以xx結尾
~: 區分大小寫匹配
~*: 不區分大小寫匹配
!~ : 區分大小寫匹配並取反
!~* : 不區分大小寫匹配並取反
+: 匹配一次或多次。和apache的類似
[0-9]: 0到9之間,[]是用來標示範圍的
[a-z] : a到z之間
() : 標示變量,()裏寫變量內容。 $1,$2,引用的就是這個變量
([a-z]) : 這個變量標示 a到z之前的這個範圍
([0-9]+) : 這個變量標示0到9之間,匹配一次或者多次。比如:2016-10-11這個字符串要寫變量匹配就是 ([0-9]+) -([0-9]+)-([0-9]+) 第8個案例有這個用法
$host : 主機名字
$request_filename : 請求的文件名字
$request_uri : 請求的uri地址
1,將www.myweb.com/connect 跳轉到connect.myweb.com
answer: rewrite /connect/(.*) /$1 permanent;
2,將connect.myweb.com 301跳轉到www.myweb.com/connect/
if ($host = connect.myweb.com) {
rewrite /(.*) http://www.myweb.com/connect/ permanent;
}
3,myweb.com 跳轉到www.myweb.com
if ($host = myweb.com) {
rewrite ^/(.*)$ http://www.myweb.com/$1 permanent;
}
4,www.myweb.com/category/123.html 跳轉爲 tutu/123.html
rewrite /category/([0-9]+).html /tutu/$1.html permanent;
5. www.myweb.com/admin/ 下內容(xx)跳轉爲www.myweb.com/admin/index.php?s=xx
if(-e $request_filename){
rewrite /admin/(.*) /admin/index.php?s=$1 permanent;
}
6.www.myweb.com/xinwen/123.html 等xinwen下面數字+html的鏈接跳轉爲404
rewrite /xinwen/([0-9]+).html /404.html permanent;
7,重定向http://www.myweb.com/123/456.php 鏈接爲404頁面
rewrite /123/456.php /404 permanent;
8.http://www.myweb.com/news/activies/2014-08-26/123.html 跳轉爲 http://www.myweb.com/news/2014-08-26/123.html (此類網頁都需跳轉)
/news/activiess/news/([0-9]+)-([0-9]+)-([0-9]+)/(.*) /news/$1-$2-$3/$4 permanent;