我有一个Amazon ELB,它监听http和httpsstream量。 它后面的实例在端口80上有nginx。仅Http。 所以ELB将https和http转发给nginx的http。
当我向https://example.com/folder等文件夹发送https请求时,会自动将其redirect到斜杠版本http://example.com/folder/,但协议将变为http。 文件夹包含index.html文件。 我认为这是它的工作原理。
有没有什么办法解决这一问题? 即使redirect到https而不是http。 我无法在全球执行https。
我的configuration:
http { map $http_x_forwarded_proto $thescheme { default $scheme; https https; } server { listen 80; server_name example.com; location / { root /var/www/html; add_header X1 $scheme; add_header X2 $thescheme; index index.html; } } }
我已经添加了X1和X2头来检查nginx认为使用什么协议,以及ELB是否添加了X-Forwarded-Proto头。 X1是http,X2是示例请求的https。
我发现添加
if (-d $request_filename) { rewrite [^/]$ $thescheme://$http_host$uri/ permanent; }
里面的位置有帮助,但想知道是否有更好的解决scheme。
我build议遵循最佳实践,而不是使用rewrite ,而是使用return指令。 使用这可能看起来像下面这样:
if ($http_x_forwarded_proto = 'http') { return 301 https://example.com$request_uri; }
另外,为了对所有发出HTTPS请求的客户端强制使用HTTPS ,请考虑添加HTTP严格传输安全(HSTS)标头。 HSTS是
一个networking安全策略机制,有助于保护网站免受协议降级攻击和cookie劫持。
为了使用它,指令可能看起来像下面这样:
add_header Strict-Transport-Security max-age=31536000;