Nginx HTTPS仅在刷新页面后有效

时间:2018-11-04 14:50:54

标签: nginx https

我为https设置了letencrypt,当没有www时,它可以正常工作。由于某种原因,我只能使'example.com'与https一起正常工作(例如,重定向到https://example.com),但是当我转到'www.example.com'时,它并不能直接转到https,在刷新页面后,它会这样做。这是我的nginx默认conf:

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似乎有效,但仅在刷新页面后有效。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

我不知道为什么这行得通,而其他答案似乎却做不到。我将顶级服务器块更改为此。可能很有用,因为我找不到这个特定问题的答案。

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;
}