目录
- Nginx if指令实现多个proxy_pass
- http模块实现
- stream模块实现
- nginx proxy_pass用法解说
- 用法
- 不同场景
- 总结
Nginx if指令实现多个proxy_pass
研究根据客户端的IP指向不同的代理端口。
http模块实现
- upstream配置
upstream webdemo1{
server 127.0.0.1:8001;
}
upstream webdemo2{
server 127.0.0.1:8002;
}
- server配置
listen 8008;
server_name 192.168.0.118;
set $jianhang false;
if ($remote_addr = \”192.168.0.105\”) {
set $jianhang true;
}
location /webdemo {
if ($jianhang = true) {
proxy_pass http://webdemo2;
break;
}
proxy_pass http://webdemo1;
}
stream模块实现
stream也想使用http模块的思路实现,经查询nginx的doc文档,发现stream不存在if指令,if指令是存在ngx_http_rewrite_module模块下的,所应用的上下文环境是:server和location。
nginx proxy_pass用法解说
用法
- 语法:proxy_pass URL;
- 默认值:无
- 上下文:一般是location内
设置某个location内上游服务器的转发协议、地址、url。
协议支持:http、 https
地址支持:域名和ip,支持设置端口号
样例:
proxy_pass http://localhost:8000/uri/;
如果一个域名能够解析出多个ip地址,则按照 round-robin轮训算法进行负载均衡。
如果一个地址是域名,优先查询该域名是否是已经定义好的upstream server group,如果是则直接使用该group的地址和回源策略。
不同场景
location /name/ {
proxy_pass http://127.0.0.1/remote/;
}
- 请求url:http://www.baidu.com/name/index.html
- 转发到后端的url:http://www.baidu.com/remote/index.html
proxy_pass 指定了uri的情况下,转发到后端的请求,将请求的uri匹配location的部分替换成proxy_pass指定的uri。
疑问:这里的标准uri是改写之后的uri,假设改写之后匹配不上location会怎么办?
location /name/ {
proxy_pass http://127.0.0.1;
}
- 请求url:http://www.baidu.com/name/index.html
- 转发到后端的url:http://www.baidu.com/name/index.html
proxy_pass没有指定uri的情况下,转发到后端的请求,将直接使用原始的请求往后转发,在经过改写的情况下,将使用改写后的标准url进行转发。
location ~ /name/ {
proxy_pass http://127.0.0.1;
}
- 请求url:http://www.baidu.com/name/index.html
- 转发到后端的url:http://www.baidu.com/name/index.html
这种情况下,location后面跟了一个正则表达式,则proxy_pass 后不能携带uri,直接按照原始url转发,在经过改写的情况下,将使用改写后的标准url进行转发。
location /name/ {
proxy_pass http://127.0.0.1$request_uri;
}
- 请求url:http://www.baidu.com/name/index.html
- 转发到后端的url:http://www.baidu.com/name/index.html
如果proxy_pass的uri部分使用变量,则完全使用该变量的值当作转发的uri,并且不再进行urlencode编码
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持悠久资源。