Nginx reverse proxy and cloudflare – Send country code to backend app

cloudflarenginxreverse-proxy

I am trying to detect the visitors country. I have the geoip option checked in the cloudflare dash and it adds a CF-IPCountry header to request headers but I am unable to pass this to my backend app through the nginx proxy. What am I doing wrong?

location / {
    # forward application requests to the gunicorn server
    proxy_pass http://localhost:8080;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header CF_IPCountry $http_cf_ipcountry; #this line is the culprit
 }

EDIT:
The backend does not see this header. I am using flask and made a route to output all the request headers.

@app.route('/headers')
def header():
    headers = request.headers
    header_list = []
    for h in headers:
        header_list.append(h)
    return jsonify(header_list)

Best Answer

By default, nginx ignores HTTP headers which contain underscores.

You have:

    proxy_set_header CF_IPCountry $http_cf_ipcountry; #this line is the culprit

But this should be:

    proxy_set_header CF-IPCountry $http_cf_ipcountry; #this line is the culprit