天天看点

一次Nginx修改跳转的实例

由于life1.cc不是我公司的域名,所以就跟对方公司的运维联系,拜托人家把这个域名绑定到我公司的nginx服务器上,绑定完之后,在我公司的nginx服务器的配置文件里加一条rewrite 301的语句,然后reload一下就可以了,感觉很简单。

在确认域名已经绑定到公司的nginx之后,我就登陆nginx,找到nginx.conf,发现里面已经include很多配置文件,节选配置如下:

1

2

3

4

5

6

7

8

9

10

<code>        </code><code>#include upstream</code>

<code>        </code><code>include upstream.conf;</code>

<code>        </code> 

<code>        </code><code># include servers</code>

<code>        </code><code>include rs.conf;</code>

<code>        </code><code>include web-cn.conf;</code>

<code>        </code><code>include web-com.conf;</code>

<code>        </code><code>include dms-smsgw.conf;    </code>

<code>}</code>

<code>server {</code>

<code>        </code><code>#web</code>

<code>        </code><code>listen 80;</code>

<code>        </code><code>listen 443 ssl;</code>

<code>        </code><code>server_name lechange.com lechange.com:443 *.lechange.com *.lechange.com:443;</code>

<code>        </code><code>chunked_transfer_encoding off;</code>

<code>        </code><code>proxy_buffering off;</code>

找到“location=/”字段做一个  rewrite,如下:

<code>location = / {</code>

<code>           </code><code>#root /mnt/hswx/nginx/html/;</code>

<code>           </code><code>#index index.html;</code>

<code>    </code><code>#rewrite ^/    redirect;   #之前一直是302跳转,于是把这个注释</code>

<code>    </code><code>rewrite ^/   permanent;    </code><code>#这个是新加的301</code>

<code>        </code><code>}</code>

<a href="https://s3.51cto.com/wyfs02/M02/92/67/wKiom1j_F4aRS4DAAAYKaYUBZWI662.png" target="_blank"></a>

清除了缓存,刷新界面但是还是302,而转用#curl看也是302,如图:

<a href="https://s1.51cto.com/wyfs02/M00/92/67/wKiom1j_F9PgHJYxAAB_dPAoe_8105.png" target="_blank"></a>

这就搞得很蒙圈了,明明在配置文件里面把301 permanent加进去了,为什么不出现301永久重定向?

后来发现了,原来nginx.conf里include字段是顺序是这样的:

#vim web-cn.conf,看到里面的server的配置: 

<code>        </code><code>server_name lechange.cn lechange.cn:443 *.lechange.cn *.lechange.cn:443;</code>

然后在下面更改了rewrite: 

<code>        </code><code>location = / {</code>

<code>                </code><code>#root /mnt/hswx/nginx/html/;</code>

<code>                </code><code>#index index.html;</code>

<code>                </code><code>rewrite ^/ https:</code><code>//www</code><code>.lechange.com permanent;</code>

<a href="https://s2.51cto.com/wyfs02/M01/92/6A/wKioL1j_OFiwjhxAAAYBK2_U5Y0098.png" target="_blank"></a>

但是细心的朋友可能会问了,文章开头的nginx.conf的include字段里明明是rs.conf最高,web-cn.conf排名是第二的,为什么不会按上下顺序去走rs.conf的配置呢?

原因是因为rs.conf里面监听的不是80端口...所以压根不会去匹配。

补充,如果在nginx本机上使用“#curl 域名:端口号”查看网页的情况,选择配置文件是“先匹配端口号,然后查看servername”;而使用“#curl IP:端口号“查看网页情况,默认选择的配置文件是匹配端口号的第一个配置文件。

感谢大华股份研发中心大数据研究院祝青雷同志解惑,碉堡了!

 本文转自 苏幕遮618 51CTO博客,原文链接:http://blog.51cto.com/chenx1242/1919371

继续阅读