nginx:带有 www-authentication 的页面上的 HSTS

Val*_*das 5 nginx https

是否可以在 nginx 上发送 Strict-Transport-Security 标头,即使是在需要 WWW-Authentication 的页面上?

当我同时拥有auth_basicand 时add_header Strict-Transport-Security "max-age=2592000";,不会发送 HSTS 标头:

$ curl -Ik https://****************
HTTP/1.1 401 Unauthorized
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 14 Sep 2014 17:56:08 GMT
Content-Type: text/html
Content-Length: 203
Connection: keep-alive
WWW-Authenticate: Basic realm="*********"
Run Code Online (Sandbox Code Playgroud)

一个不同的页面,不需要身份验证的传送,所以add_header指令是有效果-只是没有当它需要验证。

小智 5

这是可能的,但不能使用add_header指令,因为它在 401 Unauthorized 响应的情况下不会做任何事情。

ngx_http_headers_module 文档中add_header 指令的描述说:

如果响应代码等于 200、201、204、206、301、302、303、304 或 307,则将指定字段添加到响应标头。值可以包含变量。

要在每个页面上发送 HSTS 标头,您必须使用ngx_headers_more模块编译 nginx (或者nginx-extras如果您使用的是 Debian,则只需安装包),并将以下行添加到您的 nginx 配置文件中:

more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains";
Run Code Online (Sandbox Code Playgroud)


Mat*_*off 5

从 2014 年 9 月 16 日发布的 Nginx 1.7.5 开始,这可以通过alwaysadd_header指令中添加“ ”标志轻松实现。不再需要额外的模块。:-)

add_header Strict-Transport-Security "max-age=2592000" always;
Run Code Online (Sandbox Code Playgroud)

正如add_header文档现在解释的那样:

如果always指定了该参数(1.7.5),则无论响应代码如何,都将添加标头字段。

从我自己的 Web 应用程序之一(已编辑):

$ curl -I https://example.com/
HTTP/1.1 401 UNAUTHORIZED
Server: nginx/1.11.3
Date: Wed, 31 Aug 2016 15:37:59 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 17
Connection: keep-alive
WWW-Authenticate: Basic realm="example"
Strict-Transport-Security: max-age=31536000
Run Code Online (Sandbox Code Playgroud)