29

I'm currently trying to get nginx to add a header to the response when it is sending some kind of 50* error. I already have an add_header directive on the http block, and that gets respected for all requests except it seems errors. I also tried the following in one of my vhosts:

location /mediocregopheristhecoolest {
    add_header X-Test "blahblahblah";
    return 502;                                                                                                    
}       

Going to that page gives me a 502, but no header. Is this simply something nginx doesn't do, or am I doing it wrong?

sysadmin1138
  • 131,083
  • 18
  • 173
  • 296
Mediocre Gopher
  • 803
  • 1
  • 12
  • 24

2 Answers2

61

Since Nginx 1.7.5 you can use always to add a header irrespective of the response code:

add_header X-Test "blahblahblah" always;
marat
  • 711
  • 1
  • 6
  • 5
  • 1
    Frustratingly, the version in Debian's repos is currently outdated (1.6.x), but nginx [maintains their own repository](http://nginx.org/en/linux_packages.html) with the latest stable build (1.8.x right now). – kungphu Mar 02 '16 at 00:46
  • If you want to upgrade an already working debian system, debian backports is safer... https://packages.debian.org/jessie-backports/httpd/nginx The upstream package use different package organisation (may cause some downtime instead of the smooth nginx upgrade mechanism). And its postrm script removes the logs. And a couple of other small differences... – Lajos Veres Feb 02 '17 at 11:34
  • Thank you, it worked, I tried in 404 page. – Muneer Feb 13 '20 at 11:43
  • This doesn't work for me. If I make nginx reply with 502 because all the upstream servers are unavailable due to fails, it doesn't send the header. I even tried setting on the http block – Freedo Oct 27 '21 at 00:19
  • nevermind, it seems somehow wget was not displaying the header with -S, but with curl i could see it wtf – Freedo Oct 27 '21 at 00:33
23

The documentation states that add_header "Adds the specified field to a response header provided that the response code equals 200, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables." So it doesn't work with a 502.

I forgot to add that you can use the third party headers more module to add headers to other codes. You'll probably have to recompile to add it, though.

kolbyjack
  • 7,854
  • 2
  • 34
  • 29