1. 程式人生 > >常用nginx rewrite重定向-跳轉實例:

常用nginx rewrite重定向-跳轉實例:

request 判斷 rewrite html clas 鏈接 admin ces 需要

1,將www.myweb.com/connect 跳轉到connect.myweb.com

rewrite ^/connect$ http://connect.myweb.com permanent;

rewrite ^/connect/(.*)$ http://connect.myweb.com/$1 permanent;

2,將connect.myweb.com 301跳轉到www.myweb.com/connect/

if ($host = "connect.myweb.com"){

rewrite ^/(.*)$ http://www.myweb.com/connect/$1 permanent;

}

3,myweb.com 跳轉到www.myweb.com

if ($host != ‘www.myweb.com‘ ) {

rewrite ^/(.*)$ http://www.myweb.com/$1 permanent;

}

4,www.myweb.com/category/123.html 跳轉為 category/?cd=123

rewrite "/category/(.*).html$" /category/?cd=$1 last;

5,www.myweb.com/admin/ 下跳轉為www.myweb.com/admin/index.php?s=

if (!-e $request_filename){

rewrite ^/admin/(.*)$ /admin/index.php?s=/$1 last;

}

6,在後面添加/index.php?s=

if (!-e $request_filename){

rewrite ^/(.*)$ /index.php?s=/$1 last;

}

7,www.myweb.com/xinwen/123.html 等xinwen下面數字+html的鏈接跳轉為404

rewrite ^/xinwen/([0-9]+)\.html$ /404.html last;

8,http://www.myweb.com/news/radaier.html 301跳轉 http://www.myweb.com/strategy/

rewrite ^/news/radaier.html http://www.myweb.com/strategy/ permanent;

9,重定向 鏈接為404頁面

rewrite http://www.myweb.com/123/456.php /404.html last;

10, 禁止htaccess

location ~//.ht {

deny all;

}

11, 可以禁止/data/下多級目錄下.log.txt等請求;

location ~ ^/data {

deny all;

}

12, 禁止單個文件

location ~ /www/log/123.log {

deny all;

}

13, http://www.myweb.com/news/activies/2014-08-26/123.html 跳轉為 http://www.myweb.com/news/activies/123.html

rewrite ^/news/activies/2014\-([0-9]+)\-([0-9]+)/(.*)$ http://www.myweb.com/news/activies/$3 permanent;

14,nginx多條件重定向rewrite

如果需要打開帶有play的鏈接就跳轉到play,不過/admin/play這個不能跳轉

if ($request_filename ~ (.*)/play){ set $payvar ‘1‘;}
if ($request_filename ~ (.*)/admin){ set $payvar ‘0‘;}
if ($payvar ~ ‘1‘){
rewrite ^/ http://play.myweb.com/ break;
}

15,http://www.myweb.com/?gid=6 跳轉為http://www.myweb.com/123.html

if ($request_uri ~ "/\?gid\=6"){return http://www.myweb.com/123.html;}

正則表達式匹配,其中:

* ~ 為區分大小寫匹配

* ~* 為不區分大小寫匹配

* !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配

文件及目錄匹配,其中:

* -f和!-f用來判斷是否存在文件

* -d和!-d用來判斷是否存在目錄

* -e和!-e用來判斷是否存在文件或目錄

* -x和!-x用來判斷文件是否可執行

flag標記有:

* last 相當於Apache裏的[L]標記,表示完成rewrite

* break 終止匹配, 不再匹配後面的規則

* redirect 返回302臨時重定向 地址欄會顯示跳轉後的地址

* permanent 返回301永久重定向 地址欄會顯示跳轉後的地址

常用nginx rewrite重定向-跳轉實例: