HTTP解决方案
来自文档 http://nginx.org/en/docs/http/converting_rewrite_rules.html,“正确的方法是定义一个单独的服务器example.org
":
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
...
}
HTTPS解决方案
对于那些想要解决方案的人,包括https://
...
server {
listen 80;
server_name www.domain.example;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://domain.example$request_uri;
}
server {
listen 80;
server_name domain.example;
# here goes the rest of your config file
# example
location / {
rewrite ^/cp/login?$ /cp/login.php last;
# etc etc...
}
}
注意:我最初没有包括https://
在我的解决方案中,因为我们使用负载均衡器并且我们的 https:// 服务器是高流量 SSL 支付服务器:我们不会混合使用 https:// 和 http://。
要检查 Nginx 版本,请使用nginx -v
.
使用 Nginx 重定向从 URL 中去除 www
server {
server_name www.domain.example;
rewrite ^(.*) http://domain.example$1 permanent;
}
server {
server_name domain.example;
#The rest of your configuration goes here#
}
所以你需要有两个服务器代码。
使用 Nginx 重定向将 www 添加到 URL
如果您需要的是相反的,则重定向自domain.example
to www.domain.example
,你可以使用这个:
server {
server_name domain.example;
rewrite ^(.*) http://www.domain.example$1 permanent;
}
server {
server_name www.domain.example;
#The rest of your configuration goes here#
}
正如您可以想象的,这恰恰相反,并且与第一个示例的工作方式相同。这样,您就不会降低 SEO 标记,因为它是完整的永久重定向和移动。强制无 WWW 并显示目录!
下面显示了我的一些代码,以便更好地查看:
server {
server_name www.google.com;
rewrite ^(.*) http://google.com$1 permanent;
}
server {
listen 80;
server_name google.com;
index index.php index.html;
####
# now pull the site from one directory #
root /var/www/www.google.com/web;
# done #
location = /favicon.ico {
log_not_found off;
access_log off;
}
}