在AWS ELB上强制使用HTTPS

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

myapp.zip * myapp.jar 

我使用AWS CMconfiguration了一个证书,并能够通过http://www.example.comhttps://www.example.com访问我的应用程序。

现在我需要总是 强制使用 HTTPS。 我完全失去了如何做到这一点。

我看到了许多答案,如“configuration你的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; } 

我所缺less的是如何实际添加这个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 

我猜my.conf的my.conf不对。 我希望my.conf能够扩展AWS ELB的nginxconfiguration,但显然不是。 我真的想避免在我的.ebextensions有完整的nginxconfiguration。 我甚至不知道从哪里得到它。

我终于明白了。 我不得不把我的configuration放在\.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 ELBconfiguration文件中:

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

所以不需要复制/覆盖整个nginx.conf

我想提出一个更好的解决scheme来outlook未来。 Amazon ELB v1在您的Docker容器之前使用nginx作为反向代理。 当它启动类似于您的解决scheme时,您必须破解它在AWS实例上进行重写。 然而,在v2中你可以抛弃它,只是使用你自己的nginx,无论如何你都在运行。 用v2做几乎所有的事情都是非常方便的,v1在EBS初期就回来了,当时他们不知道如何使用它。