Nginx使用if指令实现多个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编码
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
- Nginx中location proxy_pass加与不加/的区别说明
- Nginx location和proxy_pass配置示例详解
- Nginx中proxy_pass的斜杠的两种方式
- Nginx的location路径与proxy_pass匹配规则说明
- Nginx捕获并自定义proxy_pass返回的错误问题
- nginx中如何配置proxy_pass
- Nginx rewrite和proxy_pass的区别及说明
- Nginx proxy_pass如何到https后端
- nginx代理参数proxy_pass的实现
- nginx反向代理proxy_pass遇到的死循环问题
- 解决nginx配置proxy_pass之后,响应变慢的问题
- Nginx中proxy_pass使用小结
相关文章
生产环境部署Nginx服务器双机热备部署keepalived的步骤(多种模式教程)
今天演示下生产环境keepalived的部署方式,安装模式有很多,比如说主备模型和双主模型,主备分:抢占模式 和 非抢占模式,对Nginx keepalived 双机热备部署相关知识感兴趣的朋友跟随小编一起看看吧2024-07-07
Nginx服务500:Internal Server Error原因之一
这篇文章主要介绍了Nginx服务500:Internal Server Error原因之一,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-05-05


最新评论