nginx http 到 https 重定向问题

nginx http to https redirection issue

我正在尝试重定向 http://example.com , https://example.com , http://www.example.com to https://www.example.com。服务器通过 ELB 通过 443 端口监听 http 和 https 请求。

nginx 配置:

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     
       }  

只有 http://example.com and https://www.example.com is working as expected.But http://www.example.com 会进入无限重定向循环。

配置文件可能有什么问题。任何帮助将不胜感激。

创建 server 块来处理重定向。

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

更新 1:

使用 X-Forwarded-Proto request header 帮助您识别客户端用于连接到您的服务器的协议(HTTP 或 HTTPS)。

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

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