如何在CentOS 7上使用Nginx将www重定向到非www

最近将wordpress部署到CentOS 7上,配置好Nginx,server_name
但总是莫名地从定向到开发的端口上

例如:
开发测试用的是http://localhost:8089
部署到服务器上,server_name设置为http://www.chenkezhao.top

然后访问http://www.chenkezhao.top,总被莫名地重定向到http://www.chenkezhao.top:8089

真悲剧!!!

话说我是怎么发现是重定向的

为了方便在服务器上使用curl测试发现的

[root@... sbin]# curl -I http://localhost
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.2
Date: Thu, 30 Nov 2017 12:26:10 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.1.12
Location: http://localhost:8089/

以下摘自:
https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7

将www重定向到非www

如果要将用户从www重定向到普通的非www域,请插入此配置:

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

重新启动Nginx

认证:使用此curl命令确保非www域重定向到www域

curl -I http://www.example.com

你应该得到一个301 Moved Permanently响应,显示非www重定向位置,如下所示:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 04 May 2015 18:20:19 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://example.com/

当然,您应该在网络浏览器(www和非www)中访问您的域名。

将非www重定向到www

如果要将用户从普通的非www域重定向到www域,请添加以下服务器块:

server {
    server_name example.com;
    return 301 $scheme://www.example.com$request_uri;
}

重新启动Nginx

认证:使用此curl命令确保非www域重定向到www域

curl -I http://www.example.com

你应该得到一个301 Moved Permanently响应,显示www重定向位置,如下所示:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 04 May 2015 18:20:19 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://www.example.com/

当然,您应该在网络浏览器(www和非www)中访问您的域名。

结论

您的Nginx永久重定向现在已经正确配置,您的用户将能够通过您的非www和www域访问您的web服务器。

发布了229 篇原创文章 · 获赞 148 · 访问量 91万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章