[Nginx] add_header Not Reflected Due to Overwrite Issue and Solution
Tadashi Shigeoka · Tue, January 7, 2020
In Nginx, when you write add_header in different directives, the settings may not be reflected and get overwritten. Here’s an introduction to this problem and its solution.
Background: Added add_header but not reflected?
The background of this issue occurred with Nginx configuration as shown in the Bad Example of Nginx add_header (Overwrite Problem) below.
The problem was that I didn’t understand Nginx’s specification where when you write add_header in a server directive and also write add_header in a location directive, all the add_header settings from the server directive disappear.
There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level.
Nginx add_header Sample Code
Bad Example of Nginx add_header (Overwrite Problem)
server {
listen 443 default ssl http2;
server_name your.example.com;
add_header X-Frame-Options SAMEORIGIN always;
add_header Strict-Transport-Security "max-age=31536000; preload" always;
location = /robots.txt {
# X-Frame-Options, Strict-Transport-Security add_header settings get overwritten and disappear
add_header content-type text/plain;
default_type text/plain;
}
}
Correct Example of Nginx add_header
server {
listen 443 default ssl http2;
server_name your.example.com;
add_header X-Frame-Options SAMEORIGIN always;
add_header Strict-Transport-Security "max-age=31536000; preload" always;
location = /robots.txt {
# Write the same add_header content as in the server directive
add_header X-Frame-Options SAMEORIGIN always;
add_header Strict-Transport-Security "max-age=31536000; preload" always;
add_header content-type text/plain;
default_type text/plain;
}
}
That’s all about solving the Nginx add_header overwrite problem from the Gemba.