在 AWS ELB 上强制使用 HTTPS

lex*_*ore 4 nginx https amazon-web-services amazon-elb

我使用自定义域在 AWS ELB 上托管了一个基于 Java 的小型 JAR 打包 web 应用程序。我上传了一个 ZIP 文件,如:

myapp.zip
* myapp.jar
Run Code Online (Sandbox Code Playgroud)

我已经配置使用AWS CM证书,我能够同时通过访问我的应用程序http://www.example.com以及https://www.example.com

现在我需要始终强制使用HTTPS 。我完全不知道该怎么做。

我看到了许多答案,例如“配置您的 nginx”:

/sf/ask/1722253431/ 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;
}
Run Code Online (Sandbox Code Playgroud)

我缺少的是如何实际将其添加到 AWS ELB nginx。

我最后尝试的是添加.ebextensions\nginx\conf.d\my.conf到我的 ZIP 档案中:

myapp.zip
* myapp.jar
* .ebextensions
  * nginx
    * conf.d
      * my.conf
Run Code Online (Sandbox Code Playgroud)

内容:

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

这给了我以下错误:

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

我想 的语法my.conf不对。我希望my.conf能扩展 AWS ELB nginx 配置,但显然没有。而且我真的很想避免在我的.ebextensions. 我什至不知道从哪里得到它。

lex*_*ore 7

我终于想通了。我只好把我的配置\.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;
}
Run Code Online (Sandbox Code Playgroud)

这会自动包含在 AWS ELB 配置文件中:

# Elastic Beanstalk Nginx Configuration File
...
http {
    ...
    server {
        ...
        # Include the Elastic Beanstalk generated locations
        include conf.d/elasticbeanstalk/*.conf;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此无需复制/覆盖整个nginx.conf.