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


 

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永久重定向 地址欄會顯示跳轉后的地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM