nginx: HSTS on a page with www-authentication
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
It is possible, but not with the add_header
directive, because it doesn't do anything in the case of 401 Unauthorized response.
Description for the add_header directive in the ngx_http_headers_module
documentation says:
Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables.
To send HSTS header on every page, you will have to compile nginx with the ngx_headers_more module (or just install nginx-extras
package if you are using Debian), and add the following line to your nginx config file:
more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains";