Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx - Forward requests to another proxy

Tags:

nginx

proxy

So, I have a third party proxy (probably under squid) which will only accept connections from one of my IP's, but I need to be able to access it from a variety of IPs.

So I'm trying to put a nginx to forward requests to this proxy. I know nginx can forward request like this:

location / {
    proxy_pass http://$http_host$uri$is_args$args;
}

This would work if I needed nginx to forward requests directly to the target site, but I need it to pass it to proxy X first. I tried this:

upstream myproxy {
   server X.X.X.X:8080;
}

location / {
   proxy_pass http://myproxy$uri$is_args$args; // also tried: http://myproxy$http_host$uri$is_args$args
}

But I get "(104) Connection reset by peer". I guess because nginx is proxying like this:

GET /index.html HTTP/1.1
Host: www.targetdomain.com.br

But I need it to proxy like this:

GET http://www.targetdomain.com.br/index.html HTTP/1.1
like image 977
lucaswxp Avatar asked Jan 05 '17 19:01

lucaswxp


1 Answers

I found out that this works:

http {
  # resolver 8.8.8.8; # Needed if you use a hostname for the proxy
  server_name ~(?<subdomain>.+)\.domain\.com$;

  server {
    listen 80;

    location / {
      proxy_redirect off;
      proxy_set_header Host $subdomain;
      proxy_set_header X-Forwarded-Host $http_host;
      proxy_pass "http://X.X.X.X:8080$request_uri";
    }
  }
}

You need to use resolver if X.X.X.X is a hostname and not an IP.

Check https://github.com/kawanet/nginx-forward-proxy/blob/master/etc/nginx.conf for more tricks.

EDIT: also check nginx server_name wildcard or catch-all and http://nginx.org/en/docs/http/ngx_http_core_module.html#var_server_name

like image 161
Silex Avatar answered Oct 23 '22 04:10

Silex