nginx http to https redirection issue

你说的曾经没有我的故事 提交于 2019-12-11 12:17:05

问题


I am trying to redirect http://example.com , https://example.com , http://www.example.com to https://www.example.com . Servers listening to both http and https requests via 443 port through ELB.

nginx config :

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

server {    
        listen       443 default;    
        server_name  www.example.com;    
        //ssl stuffs     
       }  

only http://example.com and https://www.example.com is working as expected.But http://www.example.com is going to infinite redirection loop.

What might be wrong with the config file. Any help would be appreciated.


回答1:


Create server blocks to handle the redirection.

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

Update 1:

Use the X-Forwarded-Proto request header to help you identify the protocol (HTTP or HTTPS) that a client used to connect to your server.

server {
    listen 443;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443;
    server_name www.example.com;
    if ($http_x_forwarded_proto = 'http') {
        return 301 https://www.example.com$request_uri;
    }
    // ...
}

Source: http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/x-forwarded-headers.html



来源:https://stackoverflow.com/questions/32302070/nginx-http-to-https-redirection-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!