Nginx · The edge of your stack
How do you add and forward headers in Nginx?
Short answer
Use add_header for response headers and proxy_set_header for upstream request headers. Remember add_header is inherited only when the child context has no add_header of its own.
Response and request headers are configured by different directives. add_header affects what Nginx sends to the client; proxy_set_header affects what Nginx sends to the backend. Mixing them up is a common source of missing security headers or broken host routing.
server {
server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
location /api/ {
proxy_hide_header X-Powered-By;
proxy_set_header Host $host;
proxy_set_header X-Request-Id $request_id;
proxy_pass http://backend;
}
}Inheritance and overrides
- add_header directives are inherited only if the current context has none
- The always parameter keeps a header on error responses such as 4xx and 5xx
- proxy_set_header replaces Nginx defaults for that header
- proxy_hide_header removes a backend header before sending it to the client
- The headers-more module can set or clear headers conditionally when add_header is insufficient
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why did a security header disappear in one location?
- 2What does the always parameter do?
- 3What is the difference between add_header and proxy_set_header?
- 4How do you remove a header from an upstream response?
Say it in the interview
I use add_header for client-facing response headers and proxy_set_header for headers sent to the backend. The key gotcha is inheritance: if a location has any add_header, it stops inheriting the parent's headers. I use the always flag for error responses and verify with curl -I. I also use proxy_hide_header to strip backend headers that leak implementation details.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.