在Nginx服务器上强制SSL时redirect循环

最近我一直在尝试使用Nginxredirect到HTTPS,但当我尝试在浏览器中访问我的网站后,我一直收到一个redirect循环。 这是我的完整的服务器块configuration文件:

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

search后,我发现return 301 https://$host$request_uri; 将是最简单的方法来做到这一点。

所以我实现了它到我的configuration文件,并运行sudo service nginx restart 。 然后我去了我的浏览器,我有一个redirect循环。 一旦我删除了一行代码,它就不见了。 所以我认为我真正想要的是一种更有效的redirect到SSL的方式。

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

现在,您将所有stream量redirect到https ,这对于httpstream量很有用,但是对于httpsstream量来说是非常没有意义的,并且会导致redirect循环。 现在发生的事情是: http – > https – > https – > https – > https – > https …等等,直到浏览器告诉你,“这就够了,我们不会成功“。

你想要实现的是将httpstream量redirect到https ,并处理httpsstream量(就像之前使用httpstream量那样)。

所以,你必须把你的configuration分成两个server指令:一个用于http (应该做redirect),另一个用于https ,它将处理stream量。

看看这个例子:

 server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name melone.co; return 301 https://$host$request_uri; } 

添加这个server块到你的configuration,删除现有的server块中的相应的行,并获利!

好的,我发现这个问题。 我需要两个服务器块。 一个监听端口80并redirect到443。

我将其添加到我的conf的顶部:

 server { listen 80 ; server_name melone.co; return 301 https://$server_name$request_uri; }