nginx rewrite

要解决的问题是:

所有http://www.test.com/forum.php 均跳转到 http://www.test.com/forum.php?mod=thread

其它请求仍然保持原始地址。

方法1:

原理:配置nginx rewrite来实现

操作1:rewrite ^/forum.php$ /forum.php?mod=thread last;

操作2:重启nginx

现象:能够实现跳转,但对于http://www.test.com/forum.php?gid=10这样的请求,nginx也会匹配并跳转到http://www.test.com/forum.php?mod=thread

结论是:rewrite规则中的 $貌似并不匹配结束符,该rewrite不能实现目标。

方法2:

原理:在程序中修改$mod参数实现伪跳转

代码:

if($_SERVER['REQUEST_URI'] == '/forum.php'){
 $mod = 'thread';
}

结论:如果对webserver的rewrite规则不熟,业务逻辑里跳转是个不错的选择。

方法3:

原理:还是使用nginx自带的跳转

直接上配置:

    if ($request_uri ~* "^/forum\.php$") {
        rewrite ^ /forum.php?mod=thread last;
    }   

    if ($request_uri ~* "^/forum\.php\?$") {
        rewrite ^/forum\.php\?(.*)$ /forum.php?$1 last;
    }

第一个if 仅对forum.php处理

第二个if 对forum.php?处理

 

关于nginx rewrite的示例:

实例演示

nginx官方文档---rewrite

nginx官方文档---变量

posted on 2013-09-24 15:15  awildfish  阅读(332)  评论(0编辑  收藏  举报

导航