您的位置:首页 > 运维架构 > Nginx

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

2009-06-23 18:47 696 查看
首先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里的[L]标记,表示完成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.wemvc.com/12 重定向到 http://www.wemvc.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-([0-9]+)-([0-9]+)/.html$ /forumdisplay.php?fid=$1&page=$2 last;

rewrite ^/thread-([0-9]+)-([0-9]+)-([0-9]+)/.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 属性。要匹配圆括号字符,请使用 ‘/(’ 或 ‘/)’。

^ 匹配输入字符串的开始位置。

$ 匹配输入字符串的结束位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: