【问题标题】:Nginx HTTPS only works after page is refreshedNginx HTTPS 仅在页面刷新后有效
【发布时间】:2018-11-04 14:50:54
【问题描述】:

我已经为 https 设置了letsencrypt,并且在没有 www 时可以正常工作。出于某种原因,我只能让“example.com”与 https 一起正常工作(即重定向到https://example.com),但是当我转到“www.example.com”时,它不会直接转到 https,只有在我刷新它这样做的页面。这是我的 nginx 默认配置:

server {
listen              80;
server_name         www.example.com example.com;
return              301 https://$host$request_uri;
}

server {
    # listen 80 default_server;
    # listen [::]:80 default_server;
    listen 443 ssl;
    server_name example.com www.example.com;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }



    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
}

我在 conf 中尝试了各种重定向,但似乎都没有工作。所以 https 似乎在工作,但只有在页面刷新之后。任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: nginx https


    【解决方案1】:

    我注意到您在服务器名称中使用了两个条目。 我想知道目的是什么。 请尝试此配置。

      server {
            listen      80;
            server_name www.example.com example.com;
            rewrite ^ https://$host$request_uri? permanent;
        }
    
        server {
            listen 443;
            server_name example.com www.example.com;
            root /var/www/html;
            index index.html index.htm index.nginx-debian.html;
    
            ssl on;
            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
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_prefer_server_ciphers on;
            ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
            ssl_session_cache shared:SSL:2m;    
    
    
        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
    }
    

    【讨论】:

    • 这也有效,我会接受这个作为答案,因为它更简洁。谢谢。
    【解决方案2】:

    我不知道为什么这有效,而其他答案似乎没有做同样的事情。我将顶部服务器块更改为此。可能有用,因为我找不到这个特定问题的答案。

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

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 2018-01-15
      • 2019-03-04
      • 2012-10-23
      • 2016-11-02
      • 1970-01-01
      • 2017-05-13
      • 2017-04-03
      相关资源
      最近更新 更多