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.

  • What is the full nginx configuration? Sep 15, 2014 at 0:38

2 Answers 2


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/
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";

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .