nginx重定向除一个以外的所有目录

时间:2012-07-15 15:51:52

标签: mod-rewrite nginx

我正在使用nginx 1.0.8并且我正在尝试将所有访问者从www.mysite.com/dir重定向到google搜索页http://www.google.com/search?q=dir,其中dir是变量,但是如果dir ==“blog “(www.mysite.com/blog)我只想加载博客内容(Wordpress)。

这是我的配置:

    location / {
        root   html;
        index  index.html index.htm index.php;
    }



    location /blog {
          root   html;
          index index.php;
          try_files $uri $uri/ /blog/index.php;
    }

    location ~ ^/(.*)$ {
          root   html;
          rewrite ^/(.*) http://www.google.com/search?q=$1 permanent;
    }

如果我这样做,甚至www.mysite.com/blog将被重定向到谷歌搜索页面。如果我删除最后一个位置www.mysite.com/blog效果很好。

从我在此处读到的内容:http://wiki.nginx.org/HttpCoreModule#location似乎优先级将首先出现在正则表达式上,并且与查询匹配的第一个正则表达式将停止搜索。

由于

2 个答案:

答案 0 :(得分:25)

location / {
    rewrite ^/(.*)$ http://www.google.com/search?q=$1 permanent;
}

location /blog {
      root   html;
      index index.php;
      try_files $uri $uri/ /blog/index.php;
}

答案 1 :(得分:0)

也可以仅使用正则表达式来处理这种情况。尽管这是一个非常老的问题,并且已被标记为已回答,但我要添加另一个解决方案。

如果您使用反向代理进行多次循环转发,这是最简单的方法,而不必为每个目录添加单独的位置块。

root html;
index index.php;

location / { #Match all dir
      try_files $uri $uri/ $uri/index.php;
}

location ~ /(?!blog|item2)(.*)$ { #Match all dir except those dir items skipped
      rewrite ^/(.*) http://www.google.com/search?q=$1 permanent;
}
相关问题