2

I need to set different values of custom response header based on response from the proxy_pass backend response code.

I tried many different ways, but still can't figure out how this can be done.

location /mypath {
    #for 200,301,302,etc "good" responses from 127.0.0.1:8080 I need to set value 60
    add_header X-MyCustomHeader 60;

    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;

    #for 404,403 responses from 127.0.0.1:8080 I need to set X-MyCustomHeader=5
    #for 500 responses from 127.0.0.1:8080 I need to set X-MyCustomHeader=1
}

Any help is appreciated.

vgrinko
  • 41
  • 1
  • 5
  • I doubt it is possible out of the box. You will most likely need to write either a module or a LUA script (and of course, have LUA support in your nginx installation). – Florin Asăvoaie Dec 09 '16 at 08:03

1 Answers1

2

I have come up with the following solution. it solves for the following:

  1. Set HTTP response headers based on response code from the proxy_pass backend
  2. Allow to server 404 page content from the backend, but still add headers.

Known issue:

  1. technically it will call backend twice if it is 404. For me it is not an issue, as I am caching 404 response with some small ttl. But for others it could be.

My source:

location /mypath/ {
    add_header X-MyCustomHeader 60;

    include /etc/nginx/proxy_config.conf; #some proxy_pass headers
    proxy_pass http://127.0.0.1:8080;
    proxy_intercept_errors on;
    error_page 500 502 503 504 /50x.html;
    error_page 400 403 404 =404 /mypath/errors/404.html;
}

# custom 50x fallback page for /mypath/, server from the nginx itself
location /50x.html {
    add_header X-MyCustomHeader 1;

    root html;
}

# custom 40x fallback page for /mypath/, served from the backend - hack
location /mypath/errors/404.html  {
    add_header X-MyCustomHeader 5;

    include /etc/nginx/proxy_config.conf; #some proxy_pass headers
    proxy_pass http://127.0.0.1:8080;
    proxy_intercept_errors off;
}

See this question as a reference

and this one

Are there any issues/concerns to this approach?

vgrinko
  • 41
  • 1
  • 5