Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward request headers from nginx proxy server

I'm using Nginx as a proxy to filter requests to my application. With the help of the "http_geoip_module" I'm creating a country code http-header, and I want to pass it as a request header using "headers-more-nginx-module". This is the location block in the Nginx configuration:

location / {
    proxy_pass                      http://mysite.com;
    proxy_set_header                Host http://mysite.com;;
    proxy_pass_request_headers      on;
    more_set_headers 'HTTP_Country-Code: $geoip_country_code';
}

But this only sets the header in the response. I tried using "more_set_input_headers" instead of "more_set_headers" but then the header isn't even passed to the response.

What am I missing here?

like image 923
Peleg Avatar asked Nov 03 '13 08:11

Peleg


People also ask

Does Nginx pass headers?

Passing Request HeadersBy default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, and eliminates the header fields whose values are empty strings.

What is Nginx forward proxy?

It's fast, lightweight and responsible for hosting some of the biggest sites on the internet. Nginx is often used as a load balancer, a reverse proxy, and an HTTP Cache, among other uses. In this tutorial, we are focusing on learning how to use it as a forward proxy for any requested location.


2 Answers

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

like image 106
Fleshgrinder Avatar answered Oct 26 '22 06:10

Fleshgrinder


The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

like image 66
Peter Senna Avatar answered Oct 26 '22 06:10

Peter Senna