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

来源:互联网 发布:免费物流软件 编辑:程序博客网 时间:2024/06/03 17:02

最近将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://localhostHTTP/1.1 301 Moved PermanentlyServer: nginx/1.12.2Date: Thu, 30 Nov 2017 12:26:10 GMTContent-Type: text/html; charset=UTF-8Connection: keep-aliveX-Powered-By: PHP/7.1.12Location: 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 PermanentlyServer: nginx/1.4.6 (Ubuntu)Date: Mon, 04 May 2015 18:20:19 GMTContent-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: 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 PermanentlyServer: nginx/1.4.6 (Ubuntu)Date: Mon, 04 May 2015 18:20:19 GMTContent-Type: text/htmlContent-Length: 193Connection: keep-aliveLocation: http://www.example.com/

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

结论

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