我正在尝试将 HTTPS www 请求重定向到非 www,但无法正常工作。我需要更改哪一行代码才能实现重定向?
server {
root /var/www/mydomain.com/html;
index index.html index.htm index.nginx-debian.html;
server_name mydomain.com www.mydomain.com;
#gZip stuff here...
#Certbot stuff here...
}
server {
if ($host = www.mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = mydomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name mydomain.com www.mydomain.com;
return 404; # managed by Certbot
}
答案1
我建议使用下面提到的管理方式。根据 Nginx 文档,这也是他们处理域级重定向的推荐方式。
server {
listen 443;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
listen 443;
server_name example.com;
root /var/www/mydomain.com/html;
index index.html index.htm index.nginx-debian.html;
# Others Configuration...
}
如果需要,您还可以添加一个服务器块以将 HTTP 重定向到 https。
server {
listen 80;
server_name www.example.com example.com;
return 301 https://example.com$request_uri;
}