【问题标题】:Redirect nginx www to https将 nginx www 重定向到 https
【发布时间】:2021-04-12 20:22:35
【问题描述】:

您好,我是使用 nginx 的初学者。我的网站已启动并正在运行,目前它将 http 重定向到 https。但是,如果我访问www.example.com,nginx 会将其重定向到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


}

【问题讨论】:

    标签: nginx nginx-config


    【解决方案1】:

    要做的事情是实现http -> https重定向在www。

    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

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 2016-03-10
      • 2018-06-23
      • 2016-01-07
      • 2017-03-10
      相关资源
      最近更新 更多