nginx proxy all traffic to remote nginx

2019-03-07 19:30发布

问题:

I have 2 servers,

  1. with IP xx.xx.xx.xx, situated in Germany ... (running frontend: nginx(static content), backend: Apache2)

  2. with IP yy.yy.yy.yy, situated in Italy...

All requests at the moment is sending to server with IP xx.xx.xx.xx, How can I proxy all traffic from xx.xx.xx.xx to yy.yy.yy.yy using nginx ...

          request                           proxy, request
Internet     ->       xx.xx.xx.xx(nginx)         ->             yy.yy.yy.yy(nginx, Apache)
             <-                                  <-
          response                          proxy, response

Thanks ...

回答1:

For others. Answer for subject is configure nginx like:

server {
  listen 80;
  server_name mydomain.com;
    location / {
      access_log off;
      proxy_pass http://mydomain.com:8080;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}


回答2:

You can use upsteream like:

upstream  xx.xx.xx.xx:8080{
    #ip_hash;
    server xx.xx.xx.xx:8080 max_fails=2  fail_timeout=2s;
    server yy.yy.yy.yy:8181 max_fails=2  fail_timeout=2s;
}

then you can use the cookie or header to set the request like:

location /app {
        if ($cookie_proxy_override = "proxy-target-A") {
            rewrite . http://xx.xx.xx.xx:8080/app;
            proxy_set_header  X-Real-IP       $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
            break;
        }
        if ($cookie_proxy_override = "proxy-target-B") {
            rewrite . http://yy.yy.yy.yy:8181/webreg;
            proxy_set_header  X-Real-IP       $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
            break;
        }
        proxy_pass http://xx.xx.xx.xx:8080/webreg;
        proxy_set_header  X-Real-IP       $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }