如何使用Nginx作为跨域的反向代理 [英] how to use nginx as reverse proxy for cross domains

查看:236
本文介绍了如何使用Nginx作为跨域的反向代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用nginx实现以下测试用例:

I need to achieve below test case using nginx:

www.example.com/api/应该重定向到ABC.com/api, 而www.example.com/api/site/login应该重定向到XYZ.com/api/site/login

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

但是在浏览器中,用户应该只能看到www.example.com/api....(而不是重定向的URL).

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

请让我知道如何实现.

推荐答案

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;
    }

    ...

}

(如果需要,请用https://替换http://)

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

location指令的顺序并不重要,因为作为文档状态,则选择具有最长匹配前缀的位置.

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

使用proxy_set_header参数,nginx将完全按照您所需的方式运行,并且用户将看到www.example.com/api ...否则,如果没有此参数,nginx将生成HTTP 301重定向到ABC. example.com或XYZ.example.com.

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.

您不需要在proxy_pass参数中指定URI,因为作为文档

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.

您可以将服务器ABC.example.com和XYZ.example.com指定为域名或IP地址.如果将它们指定为域名,则需要指定其他参数 resolver 在您的服务器配置中.您可以使用本地名称服务器,也可以使用外部名称服务器,例如Google公共DNS(8.8.8.8)或ISP为您提供的DNS:

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;

    ...

}

这篇关于如何使用Nginx作为跨域的反向代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆