简体   繁体   中英

how to use nginx as reverse proxy for cross domains

I need to achieve below test case using nginx:

www.example.com/api/ should redirect to ABC.com/api , while www.example.com/api/site/login should redirect to XYZ.com/api/site/login

But in the browser, user should only see www.example.com/api.... (and not the redirected URL).

Please let me know how this can be achieved.

The usage of ABC.com is forbidden by stackoverflow rules , so in example config I use domain names ABC.example.com and XYZ.example.com :

server {

    ...

    server_name www.example.com;

    ...

    location /api/ {
        proxy_set_header Host ABC.example.com;
        proxy_pass http://ABC.example.com;
    }

    location /api/site/login {
        proxy_set_header Host XYZ.example.com;
        proxy_pass http://XYZ.example.com;
    }

    ...

}

(replace http:// with https:// if needed)

The order of location directives is of no importance because, as the documentation states , the location with the longest matching prefix is selected.

With the proxy_set_header parameter, nginx will behave exactly in the way you need, and the user will see www.example.com/api... Otherwise, without this parameter, nginx will generate HTTP 301 redirection to ABC.example.com or XYZ.example.com.

You don't need to specify a URI in the proxy_pass parameter because, as the documentation states , if proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed.

You can specify your servers ABC.example.com and XYZ.example.com as domain names or as IP addresses. If you specify them as domain names, you need to specify the additional parameter resolver in your server config. You can use your local name server if you have one, or use something external like Google public DNS (8.8.8.8) or DNS provided for you by your ISP:

server {

    ...

    server_name www.example.com;
    resolver 8.8.8.8;

    ...

}

Try this:

location /api {
    proxy_pass http://proxiedsite.com/api;
}

When NGINX proxies a request, it sends the request to a specified proxied server, fetches the response, and sends it back to the client. It is possible to proxy requests to an HTTP server (another NGINX server or any other server) or a non-HTTP server (which can run an application developed with a specific framework, such as PHP or Python) using a specified protocol. Supported protocols include FastCGI, uwsgi, SCGI, and memcached.

To pass a request to an HTTP proxied server, the proxy_pass directive is specified inside a location.

Resource from NGINX Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM