Nginx: HSTS on a page with www-authentication

httpsnginx

Is it possible, on nginx, to send a Strict-Transport-Security header, even on pages that require WWW-Authentication?

When I have both auth_basic and add_header Strict-Transport-Security "max-age=2592000";, the HSTS header isn't sent:

$ 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="*********"

it is sent on a different page, that does not require authentication, so the add_header directive is having effect – just not when it requires authentication.

Best Answer

As of Nginx 1.7.5, released 16 September 2014, this is easily accomplished by adding the "always" flag to your add_header directive. Extra modules no longer required. :-)

add_header Strict-Transport-Security "max-age=2592000" always;

As the add_header documentation now explains:

If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.

From one of my own web applications (edited):

$ 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