Nginx proxy configuration to hit the backend api via http proxy

apache-2.2nginxreverse-proxy

I need the Nginx web server to connect to a https server listening on port 443. The https server cannot be reached by Nginx server machine directly and to reach the https server the nginx server needs to set the http_proxy and https:proxy parameters.

We are earlier using Apache and have achieved the same using ProxyRemote * http://10.23.45.32:3128 parameter which allows the apache server to connect to the remote https server through the proxy server.

We are in the process of moving from apache to Nginx and need to know how to add the proxy rules so that Nginx server can pass the request to https server.

I have the below configuration set up for Nginx.

server {
  listen       80;
  server_name  localhost;
  access_log  /var/log/nginx/localhost.access.log;
  location / {
         proxy_pass http://localhost:9000;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection 'upgrade';
         proxy_set_header Host $host;
         proxy_cache_bypass $http_upgrade;
  }

  #below path is working fine
  location /cities.json {
    proxy_pass      http://hostname.net:8080/cities.json;
  }
  #below rule is working fine
  location /states/ {
    proxy_pass     http://hostname.net:8080;
  }
  #below rule is giving 504 gateway timeout error.
  location /auth {
    #cannot call https://authenticationserver.net directly and need to go through proxy by setting http_proxy to http://proxy.host.net:3128
    proxy_pass    https://authenticationserver.net:443;
  }
}

In Apache, I used to do the below configuration to set the proxy:

<VirtualHost *:8000>
  ServerName hostname.net
  <Location /balancer-manager>
    SetHandler balancer-manager
    Order Deny,Allow
    Deny from all
    Allow from all
  </Location>
  <Proxy balancer://authncluster>
    BalancerMember https://target.host.net
  </Proxy>
  <Proxy *>
    Order Allow,Deny
    Allow From All
  </Proxy>
  ProxyRemote * http://proxy.host.net:3128
  SSLProxyEngine On
  ProxyPreserveHost On
  ProxyPass /balancer-manager !
  ProxyPass /authn/ balancer://authncluster/authn/
  ProxyTimeout 300
</VirtualHost>

Hope this helps. Please let me know how to do the configuration in Nginx.

Best Answer

Something like this will do it (the paths will be wrong because your question doesn't appear to specify sufficient details. The key is that nginx chooses the most specific match possible - you can ready about that here.

location / {
   proxy_pass http://localhost:9000;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection 'upgrade';
   proxy_set_header Host $host;
   proxy_cache_bypass $http_upgrade;
}

location /otherurl {
  proxy_pass http://localhost:9001;
  # etc
}

location /thirdurl {
  proxy_pass http://localhost:9002;
  # etc
}