如何使 http 到 https 重定向工作而不产生重定向循环

如何使 http 到 https 重定向工作而不产生重定向循环

我有以下 nginx conf 文件,除了 http 流量重定向到 https 之外,我想要的一切都正常工作。当我添加server_name example.com到将 http 重定向到 https 的(第一个)服务器块时,我在浏览器中收到重定向循环错误。我做错了什么。如何将 http 流量重定向到 https 而不产生重定向循环,同时保留 www 重定向到根域

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    rewrite ^(.*) https://example.com$1 permanent;
 }

 server {
     server_name  www.example.com;
     rewrite ^(.*) https://example.com$1 permanent;
 }

 server {
    server_name example.com;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    ssl_certificate /root/cert_chain.crt;
    ssl_certificate_key /root/example.com.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
            expires 30d;
            add_header Pragma public;
            add_header Cache-Control "public";
    }

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


    location /balcony-covers/ {
            return 301 $scheme://$host/balcony-screens/;
    }

    error_page 404 /404/;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

答案1

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

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

然后使用以下方法配置SSL。

server {
    listen      443;
    server_name www.example.com;

    ssl on;
    ssl_certificate     /opt/nginx/example.com/certs/example.ca-bundle;
    ssl_certificate_key /opt/nginx/example.com/certs/private/example.key;

    ssl_session_timeout  5m;

    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers   on;

    location / {
        root   /opt/nginx/example.com/public_html/www;
        index  index.html index.htm index.php;
    }

    access_log  /opt/nginx/example.com/logs/www/access.log main;

    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /opt/nginx/example.com/public_html/www$fastcgi_script_name;
        include        fastcgi_params;
}

这是基本配置,请根据您的需要进行配置:)

相关内容