0
0
Nginxdevops~15 mins

HSTS header in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Configure HSTS Header in nginx
📖 Scenario: You are managing a website server using nginx. To improve security, you want to add the HTTP Strict Transport Security (HSTS) header. This header tells browsers to always use HTTPS when connecting to your site, preventing insecure connections.
🎯 Goal: Configure nginx to send the HSTS header with a max age of 31536000 seconds (1 year) and include subdomains.
📋 What You'll Learn
Create a basic nginx server block for example.com
Add a variable for the HSTS max age value
Add the HSTS header with the max age and includeSubDomains directive
Print the final nginx server block configuration
💡 Why This Matters
🌍 Real World
Web servers use HSTS headers to force browsers to use secure HTTPS connections, protecting users from attacks like man-in-the-middle.
💼 Career
Configuring security headers like HSTS is a common task for DevOps engineers and system administrators to harden web servers.
Progress0 / 4 steps
1
Create basic nginx server block
Create a server block for example.com listening on port 443 with SSL enabled. Use ssl_certificate set to /etc/ssl/certs/example.crt and ssl_certificate_key set to /etc/ssl/private/example.key. Inside the server block, add a location / that returns status 200 with text "Welcome to example.com".
Nginx
Need a hint?

Use server { ... } block with listen 443 ssl; and specify SSL certificate paths.

2
Add HSTS max age variable
Add a variable called hsts_max_age and set it to 31536000 (seconds in one year) above the server block.
Nginx
Need a hint?

Define hsts_max_age 31536000; before the server block.

3
Add HSTS header to server block
Inside the server block, add the header Strict-Transport-Security with the value "max-age=${hsts_max_age}; includeSubDomains" using the add_header directive.
Nginx
Need a hint?

Use add_header Strict-Transport-Security "max-age=${hsts_max_age}; includeSubDomains"; inside the server block.

4
Print the final nginx configuration
Print the entire nginx configuration stored in the variable nginx_config which contains the full server block with the HSTS header.
Nginx
Need a hint?

Assign the full config string to nginx_config and print it.