Quantcast
Channel: 运维与架构 »重定向
Viewing all articles
Browse latest Browse all 2

nginx rewrite重写非www前缀域名到www前缀域名

$
0
0

一直以来我都是只解析www.nginx.cn,没有启用nginx.cn

早上看到laughing 同学给我发的邮件

直接在浏览器地址栏输入 nginx.cn 无法访问,DNS查找失败,由于您没有对域名做A记录解析 所以无法访问!

强烈建议 站长 对nginx.cn做A记录域名解析 这样可以省去输入www的麻烦,更加人性化 望采纳!!!
----------- laughing 

 

我就像按照nginx 301永久重定向配置 的方法去做

在配置文件中修改配置为

server_name nginx.cn www.nginx.cn;
if ($host ~* nginx.cn)
{
    rewrite ^/(.*)$ http://www.nginx.cn/$1 permanent;
}

kill -HUP nginx进程id

重启之后打开浏览器访问nginx.cn,一直返回502 bad gateway

开始我以为是nginx.cn的dns解析没生效,ping了一下显示已经解析生效

然后我wget nginx.cn 出现301递归重定向,在循环了20次之后退出

wget nginx.cn
 --2013-03-05 09:15:36-- http://nginx.cn/
 Resolving nginx.cn... 118.144.94.193
 Connecting to nginx.cn|118.144.94.193|:80... connected.
 HTTP request sent, awaiting response... 301 Moved Permanently
 Location: http://www.nginx.cn [following]
 --2013-03-05 09:15:36-- http://www.nginx.cn/
 Resolving www.nginx.cn... 118.144.94.193
 Reusing existing connection to nginx.cn:80.
 HTTP request sent, awaiting response... 301 Moved Permanently
 Location: http://www.nginx.cn [following]
 --2013-03-05 09:15:36-- http://www.nginx.cn/
 Reusing existing connection to nginx.cn:80.
 HTTP request sent, awaiting response... 301 Moved Permanently
 Location: http://www.nginx.cn [following]
 --2013-03-05 09:15:36-- http://www.nginx.cn/
 Reusing existing connection to nginx.cn:80.
 HTTP request sent, awaiting response... 301 Moved Permanently
 .......
 Reusing existing connection to nginx.cn:80.
 HTTP request sent, awaiting response... 301 Moved Permanently
 Location: http://www.nginx.cn [following]
 --2013-03-05 09:15:36-- http://www.nginx.cn/
 Reusing existing connection to nginx.cn:80.
 HTTP request sent, awaiting response... 301 Moved Permanently
 Location: http://www.nginx.cn [following]
 20 redirections exceeded.

 

 

仔细看了下if的相关文档,我发现if的使用是存在陷阱的:
第一个是,if ($host ~* nginx.cn)会匹配nginx.cn 和www.nginx.cn两个,这样写的结果就是造成上面的结果。
另外一个最重要的原因是,每次请都需要检查if,严重降低nginx的效率。
最好的办法是增加两个server配置

server {
  server_name www.domain.com;
  return 301 $scheme://domain.com$request_uri;
}
server {
  server_name domain.com;
  [...]
}

因此我在我的配置中增加了如下配置,就可以使用nginx.cn跳转到www.nginx.cn了。
server {
server_name nginx.cn;
return 301 $scheme://www.nginx.cn$request_uri;
}


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images