歡迎您光臨本站 註冊首頁

Nginx重定向[Rewrite]配置及示例

←手機掃碼閱讀     火星人 @ 2014-03-03 , reply:0

Nginx重定向[Rewrite]配置及示例

Nginx重定向配置及示例


今天我把webserver換成了NGINX后,發現wordpress不能用了。是NGINX不能識別apache的Rrewrite rule,後來google了一下把問題解決了!先貼代碼,后貼找到的相關文章。
vi wordpress.conf
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
server {
listen 80;
server_name www.aaronw.cn;
index index.html index.php;
include wordpress.conf;


一定要加在這裡,我開始加在location裡面發現它不生效。 Nginx重定向配置及示例
首先Apache的Rewite規則差別不是很大,但是Nginx的Rewrite規則比Apache的簡單靈活多了 Nginx可以用if進行條件匹配,語法規則類似C
if ($http_user_agent ~ MSIE) { rewrite ^(.*)$ /msie/$1 break; }
官方文檔請點擊這裡
Rewrite的Flags
Flags can be any of the following:
* last – completes processing of rewrite directives, after which searches for corresponding URI and location
* break – completes processing of rewrite directives
*redirect – returns temporary redirect with code 302; it is used if the substituting line begins with http://
* permanent – returns permanent redirect with code 301
last – 完成重寫指令后,搜索相應的URI和位置。相當於Apache里的標記,表示完成rewrite,不再匹配後面的規則。
break – 中止Rewirte,不在繼續匹配。
redirect – 返回臨時重定向的HTTP狀態302。
permanent – 返回永久重定向的HTTP狀態301。
ZEND Framework的重定向規則:
案例一:
全部重定向到 /index.php
rewrite ^/(.*) /index.php?$1&;
案例二: 如果文件或目錄不存在則重定向到index.php
if (!-e $request_filename) { rewrite ^/(.*) /index.php?$1&; }
WordPress的重定向規則:
案例一: http://www.abc.com/12 重定向到http://www.abc.com/index.php?p=12
if (!-e $request_filename) { rewrite ^/(.+)$ /index.php?p=$1 last; }
案例二: 與zendframework配置很像
if (!-e $request_filename) { rewrite ^/(.*) /index.php?$1&; }
以下為Discuz完整的Rewrite for Nginx規則
if (!-f $request_filename) {
rewrite ^/archiver/((fid|tid)-[\w\-]+\.html)$ /archiver/index.php?$1 last;
rewrite ^/forum-(+)-(+)\.html$ /forumdisplay.php?fid=$1&page=$2 last;
rewrite ^/thread-(+)-(+)-(+)\.html$/viewthread.php?tid=$1&extra=page%3D$3&page=$2 last;
rewrite ^/space-(username|uid)-(.+)\.html$ /space.php?$1=$2 last;
rewrite ^/tag-(.+)\.html$ /tag.php?name=$1 last; }
文件及目錄匹配,其中:
-f和!-f用來判斷是否存在文件
-d和!-d用來判斷是否存在目錄
-e和!-e用來判斷是否存在文件或目錄
-x和!-x用來判斷文件是否可執行
正則表達式全部符號解釋
~ 為區分大小寫匹配
~* 為不區分大小寫匹配
!~和!~* 分別為區分大小寫不匹配及不區分大小寫不匹配
(pattern) 匹配 pattern 並獲取這一匹配。所獲取的匹配可以從產生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。要匹配圓括弧字元,請使用 『\(』 或 『\)』。
^ 匹配輸入字元串的開始位置。
$ 匹配輸入字元串的結束位置。

本文出自王煒個人網站:http://aaronw.me/static/222.html

[火星人 ] Nginx重定向[Rewrite]配置及示例已經有843次圍觀

http://coctec.com/docs/service/show-post-2264.html