将 https://www 重定向至 https

将 https://www 重定向至 https

我尝试过在这里和 digital ocean 上回答其他问题,但都没有用。我使用的是 nginx,到目前为止,如果我输入www.example.com页面加载失败,但当我尝试使用 https 时,页面加载成功。如何将 www 重定向到 https?我尝试在服务器块 3 中执行此操作。

Nginx 配置:

   # Server block 1
    server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;

        server_name _;

        location / {
                try_files $uri $uri/ =404;
        }
}


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

# Server block 2
server {

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        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 block 3
    server {
        if ($host = example.com) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
        if ($host = www.example.com) {
            return 301 https://$host$request_uri;
        }
    
            listen 80 ;
            listen [::]:80 ;
        server_name www.example.com example.com;
        return 404; # managed by Certbot
    
    
    }

答案1

为什么不直接将 www 设为 DNS 中 @ 的 CNAME 然后就完事了?

相关内容