【问题标题】:Forcing HTTPS when using opsworks nginx and ELB to terminate SSL使用 opsworks nginx 和 ELB 终止 SSL 时强制使用 HTTPS
【发布时间】:2023-04-10 01:42:01
【问题描述】:

对通过 Unicorn/nginx 层提供服务的 Rails 应用程序使用 Opsworks 标准设置/配方。 SSL 在 Elastic Load Balancer 处终止 - 因此从 ELB 到 rails 应用程序的流量始终是 http。到目前为止,一切都很好。我想有任何请求 http://domain.com 被重定向到 https://domain.com

ELB 有两个侦听器 - 一个使用端口 80,一个使用 443。

我知道,如果我运行自己的 nginx,我可以设置重定向规则......但是,如果可能,我想留在 opsworks 的做事方式中。

【问题讨论】:

  • 你有没有找到任何帮助你解决这个问题的东西? Opsworks 的做法是什么?我按照他们的文档进行操作,但 ELB 仍然在浏览器中终止/杀死/抛出错误,但我可以输入 IP 地址,它将通过。
  • 我最终把它保持得非常简单,并在发生从 http 到 https 的重定向的地方使用了 CloudFlare。所以ELB保持在https上,根本不需要打开http端口。

标签: nginx aws-opsworks


【解决方案1】:

我很确定你必须在你的应用服务器上使用 nginx 来处理重定向 http -> https。 这里有两种方法可以解决这个问题。

  1. 将所有请求从 80 重定向到 https:

    server {
       listen 80;
       return 301 https://example.com/$request_uri;
    }
    
  2. ELB 支持名为 X-FORWARDED-PROTO 的标头。 通过 ELB 的所有 HTTPS 请求都将具有 X-FORWARDED-PROTO = “HTTPS” 的值:

    server {
        listen 80;
        location / {
            if ($http_x_forwarded_proto != 'https') {
                rewrite ^ https://$host$request_uri? permanent;
            }  
        }
    }
    

【讨论】:

    【解决方案2】:

    我认为在 OpsWorks 中执行此操作的唯一方法是创建一个修改 /etc/nginx/sites-available/#{application} 的自定义配方。在您的自定义食谱中:

    somecookbook/recipes/nginx.rb

    node[:deploy].each do |application, deploy| 
    
          service "nginx" do
            supports :status => true
            action :nothing
          end
    
          # Add HTTP => HTTPS redirect      
          template "/tmp/http_redirect.conf" do
            source "nginx/http_redirect.conf.erb"
          end
    
          execute "redirect HTTP to HTTPS" do
            cwd "/etc/nginx/sites-available"
            command "cat #{application} /tmp/http_redirect.conf > /tmp/#{application}.conf && cat /tmp/#{application}.conf > #{application}"
            notifies :restart, "service[nginx]", :immediately
          end                                      
      end    
    end
    

    然后在配置中:

    somecookbook/templates/default/nginx/http_redirect.conf.erb

    server {
        listen       80;
        rewrite ^(.*) https://$host$1 permanent;
    }
    

    【讨论】:

    • 非常感谢!只是一个错字,应该是 http_redirect.conf.erb 模板文件扩展名的“.erb”
    猜你喜欢
    • 2011-05-22
    • 2018-08-13
    • 2014-08-25
    • 2017-08-22
    • 1970-01-01
    • 2010-11-22
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多