nginx http到https重定向问题 [英] nginx http to https redirection issue

查看:492
本文介绍了nginx http到https重定向问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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     
       }  

http://example.com https:// www .example.com 按预期工作。但 http://www.example.com 正在进行中到无限重定向循环。

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.

推荐答案

创建服务器块来处理重定向。

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请求标头来帮助您识别客户端用于连接的协议(HTTP或HTTPS)到你的服务器。

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

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

这篇关于nginx http到https重定向问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆