将 nginx www 重定向到 https

Redirect nginx www to https

您好,我是使用 nginx 的初学者。我的网站已启动 运行,目前它会将 http 重定向到 https。但是,如果我访问 www.example.com nginx will redirect it to https://www.example.com。我怎样才能让 www 重定向到 https?

我的 nginx 配置如下:

    server {
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name _;
        location / {
                try_files $uri $uri/ =404;
        }
}

upstream my_nodejs_upstream {
 server 127.0.0.1:5000;
 keepalive 64;
}

server {
        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;
      server_name example.com; # managed by Certbot

        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_set_header X-NginX-Proxy true;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection upgrade;
                proxy_max_temp_file_size 0;
                proxy_pass http://my_nodejs_upstream/;
                proxy_redirect off;
                proxy_read_timeout 240s;
        }

        location /api {
                proxy_pass http://localhost:3001;


    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80 ;
        listen [::]:80 ;
    server_name example.com;
    return 404; # managed by Certbot


}

在 www 上实现 http -> https 重定向的方法

  1. 将 www. 添加到服务器块中的服务器名称,如下所示:
server_name example.com; # managed by Certbot

server_name example.com www.example.com; # managed by Certbot
  1. 确保 www. 的 A 记录(创建子域 www. 如果不可用)指向来自您域的 dns 的服务器 ip。
  2. 为新服务器块重新生成证书。

现在您可以将 http:// 和 http://www. 重定向到 https