‹‹ Go to homepage

Route nginx proxy through another http proxy

08 of February, 2016


There are tons or articles about setting up a reverse proxy using Nginx. Just search the stackoverflow and you will receive a lot results - I’m not going to repeat it here.

I will be talking about more specific case. Imagine you have to setup a reverse proxy for a website, which you have to route via http proxy. Maybe due to some complicated logging, tracking or permissions.

It’s not complicated:

  1. Define your http proxy as an upstream server;
  2. Proxy the response to it, instead of the server, whcih you are proxying;
  3. Rewrite the uri to contain the protocol and the hostname, otherwise proxy will get confused.

Gotcha #1: rewrite in two steps, otherwise nginx will do a 302 redirect as soon as it will detect a redirect with full domain and a protocol like “http://”.

Gotcha #2: don’t break after first step, otherwise nginx will send request without a valid protocol.

upstream http-proxy-server {
    hostname.of.http.proxy.server:8080;
}
server {
    listen 80;
    server_name hostname.which.customer.sees;
    location / {
        rewrite ^(.*)$ "://hostname.of.proxied.server$1";
        rewrite ^(.*)$ "http$1" break;
        proxy_pass http://http-proxy-server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host hostname.of.proxied.server;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

The limitation of this example is that it supports only http protocol.

comments powered by Disqus