在 Nginx 服务器上强制使用 SSL 时重定向循环

cme*_*one 2 ssl nginx https tls 301-redirect

最近我一直在尝试使用 Nginx 重定向到 HTTPS,但是在我尝试在浏览器中访问我的网站后,我不断收到重定向循环。这是我的完整服务器块配置文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    listen 443 ssl;

    root /var/www;
    index index.php index.html index.htm home.html contact.html projects.html;

    # Make site accessible from http://localhost/
    server_name melone.co;
    return 301  https://$host$request_uri;
    ssl_certificate /path/to/ssl;
    ssl_certificate_key /path/to/ssl;


    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        proxy_set_header        X-Forwarded-Proto $scheme;
    }
    error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        root /var/www;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

}
Run Code Online (Sandbox Code Playgroud)

在四处搜索后,我发现这return 301 https://$host$request_uri;将是最简单的方法。

所以我将它实现到我的配置文件中,然后运行sudo service nginx restart. 然后我去了我的浏览器,我得到了一个重定向循环。一旦我删除了那一行代码,它就消失了。所以我认为我真正在寻找的是一种更有效的重定向到 SSL 的方法。

任何帮助,将不胜感激。谢谢

gf_*_*gf_ 8

就目前而言,您将所有流量重定向到https,这对http流量有好处,但对于https流量来说毫无意义,并导致重定向循环。现在发生的事情如下:http-> https-> https-> https-> https-> https... 等等,直到你的浏览器告诉你,“够了,我们不会成功” .

您想要实现的是将http流量重定向到https,并处理https流量(就像您之前对http流量所做的那样)。

因此,您必须将配置拆分为两个server指令:一个 for http(应该执行重定向),另一个 forhttps将处理流量。

看看这个例子:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name melone.co;
    return 301 https://$host$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

将此server块添加到您的配置中,删除现有server块中的相应行,然后获利!