Edit a header value in nginx

2019-04-07 13:53发布

问题:

Background
So I've got a server running a tomcat application hidden behind an Apache proxy. The proxy provides a more user friendly url as well as SSL encryption with automatic redirects so that the app is only accessible on https.

I'm busy migrating this to an nginx proxy.

One of the issues I've had is that upon login, my app sends back a "LocationAfterLogon" header in the http response in the form of

http://192.168.x.x:8080/myapp/index.jsp. 

That IP address returned is from the proxied server not visible on the internet. So then the browser gets a connection error trying to navigate to it.

As a workaround, I've used nginx directives:

  • proxy_hide_header: to hide the LocationAfterLogin header coming back from the proxied server
  • add_header: to add a new LocationAfterLogin url.

So my config looks as follows

            #header for location after logon of demo app
            add_header LocationAfterLogon http://example.com/demo/index.jsp;
            #hide the real LocationAfterLogon
            proxy_hide_header LocationAfterLogon;

The Problem
I need to be able to do a regex replace or similar on LocationAfterLogon because it won't always be to index.jsp, depending on which url was intercepted by the login page.

I am aware that I can also rewrite the tomcat app to send back a relative URL instead, but I'd like to do it all in nginx config.

I've also read about nginx more_set_headers. Haven't tried it yet. Does it allow me to edit the headers?

Apache has the Header edit directive which I was using previously, so I'm looking for something like that.

TL;DR
Is is possible to edit a header location using regex replace or similar in Nginx?

回答1:

You can use the map directive to rewrite your header:

 map $upstream_http_locationafterlogon $new_location {
     ~regexp   new_value;
 }

 proxy_hide_header LocationAfterLogon;
 add_header LocationAfterLogon $new_location;

See the documentation: http://nginx.org/en/docs/http/ngx_http_map_module.html



标签: nginx