如何使用nginx将请求redirect到不同的域/ URL

我正在尝试将所有来到“ http://example.com/something ”url的用户redirect到“ http://answares.com/examples_com/something ”之类的url。

我试着用这样的代码:

server { listen 1.2.3.4:80; server_name "example.com"; rewrite ^(.*) http://answares.com/examples_com$1 permanent; } 

通过访问“ http://example.com/ ”我被redirect到“ http://answares.com/examples_com/ ”,但通过访问“ http://example.com/something ”,我被redirect到:“ http ://answares.com/something “。

我试图以不同的方式做到这一点,但我得到的最好的是:

 http://answares.com/examples_com//something 

这是因为两个斜线看起来跛脚。 我在Ubuntu 10.4上使用Nginx 0.7.65

最快的方法是做一个return而不是一个重写。 看这里:

nginxredirect到www.domain

我刚刚回答了这个问题,并对这个问题重重一下。

如果你只是想redirect/something ,而没有其他的url,那么:

 rewrite ^(/something.*) http://answares.com/examples_com$1 permanent; 

这会向http://example.com/something/发送请求http://answares.com/examples_com/something/

也就是说, http://example.com/something/somewhere/page.html http://answares.com/examples_com/something/somewhere/page.html http://example.com/something/somewhere/page.html http://answares.com/examples_com/something/somewhere/page.html

你可以做:

  rewrite ^/(.*)$ http://answares.com/examples_com/$1 permanent; 

这给你带来了:

 $ curl -I http://xxxxx.com/some/example/url/here.html HTTP/1.1 301 Moved Permanently Server: nginx/0.8.53 Date: Mon, 05 Sep 2011 13:48:23 GMT Content-Type: text/html Content-Length: 185 Connection: keep-alive Location: http://answares.com/examples_com/some/example/url/here.html 

要么

 rewrite ^(/.*)$ http://answares.com/examples_com$1 permanent; 

你可以看到它也可以工作:

 $ curl -I http://xxxxxx.com/some/example/url/here.html HTTP/1.1 301 Moved Permanently Server: nginx/0.8.53 Date: Mon, 05 Sep 2011 13:47:09 GMT Content-Type: text/html Content-Length: 185 Connection: keep-alive Location: http://answares.com/examples_com/some/example/url/here.html 

nginxredirect和mod_rewriteredirect之间的区别在于nginx在匹配之前不会删除服务器名称之后的斜杠(/)。

为了消除双斜杠,你应该首先匹配正则expression式中的斜杠而不用括号,然后应用匹配; 或匹配所有内容,并且不带括号地应用匹配。 使用这种或那种方式只是一个品味问题;-)