嗨,这肯定是一个基本问题,但我还没有看到关于 cerbot 考虑的答案(如果有任何考虑的话)。如何让 https www 重定向到非 www 而不是超时?
这https www我的网站版本超时而不是重定向到非 www,而所有其他版本(http 和 https 非 www)都运行正常。
最好我想要面向未来,以便我可以通过 certbot 更新证书,而不需要在之后手动更改 nginx 配置。
nginx 服务器配置如下所示:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name www.mydomain.com mydomain.com;
listen 443 ssl; # managed by Certbot
ssl_certificate <path_to_cert> # managed by Certbot
ssl_certificate_key <path_to_key>; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam <path_to_this>
if ($scheme != "https") {
return 301 https://$host$request_uri;
} # managed by Certbot
}
答案1
您对 http/s 和 www/non-www 的四种变体分别使用单独的服务器块。如果可以用其他方式做事,则永远不要使用“if”语句 -Nginx If 是邪恶的。
# http server, static websites
server {
server_name example.com;
listen 443 ssl http2;
ssl_certificate /var/lib/acme/certs/***CERT_DIRECTORY/fullchain;
ssl_certificate_key /var/lib/acme/certs/***CERT_DIRECTORY/privkey;
root /var/www/***rootdir;
}
# This server simply redirects the requested to the https version of the page
server {
listen 80;
server_name www.example.com example.com;
# Let's Encrypt certificates with Acmetool
location /.well-known/acme-challenge/ {
alias /var/www/.well-known/acme-challenge/;
}
location / {
return 301 https://example.com$request_uri;
}
}
server {
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate /var/lib/acme/certs/***CERT_DIRECTORY/fullchain;
ssl_certificate_key /var/lib/acme/certs/***CERT_DIRECTORY/privkey;
return 301 https://example.com$request_uri;
}