如何在 nginx 中将 https://www 重定向到 https://?

如何在 nginx 中将 https://www 重定向到 https://?

我正在尝试重定向https://www在 nginx 中访问 https:// 但从未成功。以下是我的配置文件:

server {
listen 80;
listen [::]:80; # 
server_name example.com www.example.com;
return 301 https://example.com$request_uri;

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
index index.php;

root /home/username/sites/example.com/public;

ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";

}

我错过了什么?

谢谢

答案1

您缺少用于处理 HTTPS 的 www.example.com 的服务器块:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
    ssl_certificate "/etc/letsencrypt/live/www.example.com/fullchain.pem";
    ssl_certificate_key "/etc/letsencrypt/live/www.example.com/privkey.pem";
}

不要忘记它的证书。

相关内容