Nginx rewrite模塊

Nginx rewrite模塊

1.詳細文檔

淘寶團隊翻譯的詳細文檔

http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_rewrite_module.html

2.簡介

ngx_http_rewrite_module模塊允許正則替換URI,返回頁面重定向,和按條件選擇配置

執行順序:
    1,server級別的定義
    2,location定義的模塊指令
    3,如果location中重新向別的location,則再執行新的location中的定義指令。
       如果這個循環重複10次,nginx則報500錯誤

2.配置指令

1.if
    if ( condition ){ ... }
    上下文:server,location
    注意:血的教訓,if和括號之間一定要有一個空格,沒有的話報錯

    condition:
        #1.變量,如果爲空或者0開頭字符則爲假
        #2.=和!= 做比較 
        #3.使用“-f”和“!-f”運算符檢查文件是否存在;
        #4.使用“-d”和“!-d”運算符檢查目錄是否存在;
        #5.使用“-e”和“!-e”運算符檢查文件、目錄或符號鏈接是否存在;
        #6.使用“-x”和“!-x”運算符檢查可執行文件
        #7.~區分大小寫 *~不區分大小寫,匹配變量和正則表達式。如果含有敏感字符`{`,`}`,`;`則表達式需要引號
                                    匹配到的字符按照匹配到的順序用$1-$9代替

2,break
    上下文:server,location,if
    停止處理當前這一輪的ngx_http_rewrite_module指令集

3,return 
    上下文:server,location,if

       return code text
       return code url;
       return url;

    location ~ .*\.(sh|bash)?${
        return 500;
    }

4,rewrite / rewrite_log

    rewrite regex replacement [flag]
    上下文:server,location,if
    flag參數:last,break,redirect,permanent
        #last           匹配完成後,繼續向下匹配新的location URL規則,超過10次則500.
                        也就是rewrite匹配成功後根據新的規則繼續向下匹配,不能超過10次
        #break          rewrite匹配成功後終止,不繼續向下匹配任何其他規則
        #redirect       返回302臨時重定向,瀏覽器地址會顯示跳轉後的URL地址
        #permanent      返回301永久重定向,瀏覽器地址欄會顯示跳轉後的URL地址

    語法:     rewrite_log on | off;
    默認值:    rewrite_log off;
    上下文:    http, server, location, if

5,set 

    語法:     set variable value;
    默認值:    —
    上下文:    server, location, if

3.實例

rewrite中,最常用的就是rewrite regex replacement [flag] if等。
上面是簡單理論知識,後續會維護本實例,讓內容越來越豐富

127.0.0.1/public/index.php?id=8&type=1 重寫爲127.0.0.1/public/index/id/8/type/1.html
#這樣就把127.0.0.1/public/index/id/8/type/1.html重寫爲標準的.php?param=value格式
location ~ \.html {
    rewrite ^/public/index/id/(.*)/type/(.*).html$ /public/index.php?id=$1&type=$2 last
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章