nginx http to https redirection issue

2019-08-07 13:52发布

问题:

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