Nginx

在 AWS ELB 上強制使用 HTTPS

  • January 24, 2017

我使用自定義域在 AWS ELB 上託管了一個基於 Java 的小型 JAR 打包 web 應用程序。我上傳了一個 ZIP 文件,例如:

myapp.zip
* myapp.jar

我已經使用 AWS CM 配置了一個證書,並且能夠http://www.example.com通過https://www.example.com.

現在我需要始終**強制使用HTTPS 。我完全不知道該怎麼做。

我看到了很多答案,比如“配置你的 nginx”:

https://stackoverflow.com/questions/24603620/redirecting-ec2-elb-from-http-to-https https://aws.amazon.com/de/premiumsupport/knowledge-center/redirect-http-https-elb/ http://www.emind.co/how-to/how-to-force-https-behind-aws-elb/

其他答案朝著相同的方向發展。

雖然我可以理解重寫器規則的想法,例如:

if ($http_x_forwarded_proto = 'http') {
   return 301 https://www.example.com$request_uri;
}

我缺少的是如何實際添加這個 AWS ELB nginx。

我最後嘗試的是添加.ebextensions\nginx\conf.d\my.conf到我的 ZIP 存檔中:

myapp.zip
* myapp.jar
* .ebextensions
 * nginx
   * conf.d
     * my.conf

內容:

if ($http_x_forwarded_proto = 'http') {
   return 301 https://www.example.com$request_uri;
}

這給了我以下錯誤:

2016/12/24 12:08:27 [emerg] 22709#0: "if" directive is not allowed here in /var/elasticbeanstalk/staging/nginx/conf.d/myconf:1

我猜 sytnax ofmy.conf是不正確的。我希望my.conf能擴展 AWS ELB nginx 配置,但顯然它沒有。而且我真的很想避免在我的.ebextensions. 我什至不知道從哪裡得到它。

我終於想通了。\.ebextensions\nginx\conf.d\elasticbeanstalk\*.conf例如,我必須將我的配置放入\.ebextensions\nginx\conf.d\elasticbeanstalk\force-https.conf

內容是:

if ($http_x_forwarded_proto = 'http') {
   return 301 https://www.example.com$request_uri;
}

這會自動包含在 AWS ELB 配置文件中:

# Elastic Beanstalk Nginx Configuration File
...
http {
   ...
   server {
       ...
       # Include the Elastic Beanstalk generated locations
       include conf.d/elasticbeanstalk/*.conf;
   }
}

所以不需要複製/覆蓋整個nginx.conf.

引用自:https://serverfault.com/questions/822592