簡體   English   中英

在ELB上使用Nginx將HTTP流量重定向到https

[英]Redirect http traffic to https using Nginx on ELB

我在嘗試將http流量發送到https時遇到了一些麻煩。 因此,我正在使用來自AWS的Elastic Beanstalk來部署一個名為Augustysixpad.me的Rails 5應用程序。 我已經配置了SSL,因此當您訪問https://www.eightysixpad.me時,它說的很安全,我很高興。 但是,當您訪問http://時,它說不安全,我無法弄清楚如何重定向流量。

我對Nginx和Web應用程序非常陌生,因此對它的任何幫助將不勝感激! 我已經進入我的EC2實例,並嘗試使用以下配置設置配置在/etc/nginx/nginx.conf中的Nginx配置文件。

server {
    listen         80;
    server_name   eightysixpad.me;
    if ($http_x_forwarded_proto != "https") {
      rewrite ^(.*)$ https://$server_name$1 permanent;
    }
    root         /usr/share/nginx/html;
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

但是,沒有運氣:(我很確定我使用的是正確的文件,但是如果我進行任何認為會破壞該站點並且無法正確加載的更改,該站點仍然可以運行。所以我的第一個問題是,這是正確的文件嗎? /etc/nginx/nginx.conf ,如果不是,nginx配置保存在什么地方;第二,如果文件正確,我在做什么錯?

還有其他疑問或更多信息,請告訴我!

先感謝您!

您懷疑/etc/nginx/nginx.conf不是進行更改的正確位置,這是正確的。 ElasticBeanstalk使用一個單獨的位置來存儲nginx配置文件,即/opt/elasticbeanstalk/support/conf 在該目錄中,您會找到名為nginx_config.erbnginx_config_healthd.erb文件,它們是用於在運行時動態生成nginx配置的模板。

話雖如此,您根本不需要弄混配置文件。 如果在production.rb設置config.force_ssl = true ,則所有http連接都應重定向到https。 有關更多詳細信息,請參見文檔

斯科特·布拉德利(Scott Bradley)的博客(以下鏈接)很好地總結了該問題以及如何在ELB后面的nginx上解決該問題:

ELB后面的Nginx始終在線HTTPS

該解決方案由兩個主要組件組成:

健康檢查URL的特定位置指令,不執行任何HTTPS強制執行。 如果X-Forwarded-Proto:https標頭不存在,則為重定向。 為了獲得最佳實踐,我們也可以在此處使用add_header指令添加HTTP Strict Transport Security。 下面是一個簡化的nginx配置文件示例,展示了這些內容。

upstream unicorn {
  server localhost:3000;
}

server {
  listen 90;
  server_name example.com;
  root /var/www/html;

  # 1) Special, somewhat redundant location to always proxy
  #    the health check to the upstream server, without checking
  #    if the request came in over HTTP or HTTPS.
  location /health_check {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_next_upstream error;
    proxy_pass http://unicorn;
    break;
  }

  # Our main location to proxy everything else to the upstream
  # server, but with the added logic for enforcing HTTPS.
  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_next_upstream error;

    # 2) Any request that did not originally come in to the ELB
    #    over HTTPS gets redirected.
    if ($http_x_forwarded_proto != "https") {
      rewrite ^(.*)$ https://$server_name$1 permanent;
    }

    proxy_pass http://unicorn;

    # Add HTTP Strict Transport Security for good measure.
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains;";
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM