使用负载均衡器后面的 ngnix 将 http 重写为 https

jwe*_*rre 13 nginx load-balancing

我正在使用 Rackspace 负载平衡器,它使我能够在管理面板内设置我的 ssl 密钥/pem。一切正常,我可以同时使用 http 和 https 协议。但是,如果我尝试使用以下方法将 http 重定向到 https:

server{
  listen *:80;
  server_name mydomain.com www.mydomain.com; 
  rewrite ^ https://mydomain.com$request_uri? permanent;
Run Code Online (Sandbox Code Playgroud)

...我得到一个重定向循环。我意识到我没有在监听端口 443,但那是因为负载均衡器为我处理了这个。我也尝试将重写包装起来if ($scheme ~* http){无济于事。

我的问题的另一部分是我想从 url 中删除 www,我可以通过一次重写来做到这一点吗?上面的重写不应该处理这个问题吗?

谢谢你的帮助!

Luk*_*son 23

通过使用 nginx 的内置服务器变量$request_uri$server_name您可以完全不使用正则表达式。将以下内容添加到您的服务器location块中,您就完成了:

if ($http_x_forwarded_proto = "http") {
    return 301 https://$server_name$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

这假设您的负载均衡器将$http_x_forwarded_proto标头与请求一起发送到您的后端实例。其他常见的标头包括$http_x_forwarded_scheme并且也只是$scheme.

更多信息可以在 nginx陷阱和常见错误文档中找到:https : //www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites

  • 绝对应该使用 return 重写。赞成。 (5认同)
  • 你可以使用 `$host` 代替 `$server_name` (4认同)

小智 14

sciurus 是正确的,因为当 SSL 在负载均衡器上卸载时,Rackspace 的云负载均衡器将 X-Forwarded-Proto 设置为 https。为了避免 nginx 中的重定向循环,您应该能够将以下内容添加到locationvhost 配置中的部分:

if ($http_x_forwarded_proto = "http") {
            rewrite  ^/(.*)$  https://mydomain.com/$1 permanent;
}
Run Code Online (Sandbox Code Playgroud)

这应该在将非 https 请求重定向到 https 时避免无限重定向循环。