I want to change the cache control header when there's an HTTP redirect related code (30x).

How can I check the response's HTTP code to see if I should run add_header

  • 1
    Great question! I'm amazed it got so little attention! – cnst Aug 28 '17 at 1:08

The following should work:

server {
    listen 60729;
    error_page 301 @301;
    return 301 http://example.su/test;
    location @301 {
        add_header X-Header value;
        return 301 $sent_http_location;

Here's the confirmation:

%curl -v localhost:60729 | & fgrep \
    -e HTTP/ -e X-Header -e Location -e title | sed 's#^#\t#g'
> GET / HTTP/1.1
< HTTP/1.1 301 Moved Permanently
< Location: http://example.su/test
< X-Header: value
<head><title>301 Moved Permanently</title></head>

Note that each part of the config is quite important:

  • the error_page directive effectively provides a very neat exception handling capabilities to nginx;

  • without return 301 within location @301, nginx will try to serve the requisite file from the filesystem; this will likely result in a 404, so, you'll get a 404 page; note that the Location header would still be preserved, but the X-Header will be missing from a 404 Not Found page, because, as per the documentation of the add_header directive, it doesn't let you add headers to error pages;

  • with a plain return 301; within location @301, you will effectively clear out the Location, so, your Location would be empty; thus you have to use $sent_http_ to preserve the current value.

If you want to try out my POC MVP as above, you can find the full config in my GitHub at https://github.com/cnst/StackOverflow.cnst.nginx.conf.


This should work if you're doing the redirects within nginx. You'll have to build Nginx with the headers_more module which is pretty easy - see my Nginx tutorial here.

 location /match/ {
   add_header HEADER_NAME "header value";
   return 301 https://example.com;

If you're proxying through to an application that's returning redirects then it would be a little more complex, probably involving IF statements. IF in nginx doesn't always work as you expect, so you may be best off changing the application in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.