Home / How to enable HSTS (HTTP Strict Transport Security) in Nginx?

How to enable HSTS (HTTP Strict Transport Security) in Nginx?

nginx

In NGINX, configure the Strict Transport Security (STS) response header by adding the following directive in nginx.conf file.

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

add_header directives are inherited by NGINX configuration blocks from their enclosing blocks, so the add_header directive only needs to be in the top-level server block.

There is one important exception: if a block includes an add_header directive, it does not inherit headers from enclosing blocks, and all add_header directives must be redeclared. Consider the following scenario.

server {
listen 443 ssl;

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# The 'location' block inherits the STS header
location / {
root /usr/share/nginx/html;
}
# As this 'location' block contains another 'add_header' directive,
# STS header should be redeclared
location /servlet {
add_header X-Served-By "My Servlet Handler";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
proxy_pass http://localhost:8080;
}
}

Only HTTPS is supported by HSTS. It’s not going to work with HTTP.

Leave a Reply