nginx下的proxy_pass使用

之前的文章说到了,return,rewrite的使用,以及它们的使用场景,今天再来说一种代理的使用,proxy_pass,它属于nginx下的ngx_http_proxy_module模块,没有显示的重定向(看不到30x的重定向),客户端是不知道的,是服务器内部进行转发的

浏览器访问地址:http://m.9000.local/index/get,执行代码如下:

$a = file_get_contents("http://return.local/redirect?a=1&b=2");
$a = Tools::https_request("http://return.local/redirect?a=1&b=2", [
    'aa' => 1,
    'bb' => 2,
    'cc' => 3,
    'dd' => 4
]);//此处使用curl post方式发起请求
echo $a;

return.local的nginx配置如下:

server {
	listen        80;
	server_name  return.local;
    
	location /redirect {
		proxy_pass http://m.9000.local/index/api;
	}
}

http://m.9000.local/index/api的执行代码如下:

echo '请求方式:'.$_SERVER['REQUEST_METHOD'];

echo '<hr>';
echo 'get请求的参数';
print_r($_GET);

echo '<hr>';
echo 'post请求的参数';
print_r($_POST);

执行结果如下:

结论

1、proxy_pass代理 ,把请求方式,get参数,post参数,到代理到新地址了,且客户端没有发生显示的重定向

2、无论是浏览器请求,postman,或者curl,客户端请求,都能成功

注意

proxy_pass地址有个斜杠(/)的问题要注意下,举例说明

代理地址后面没有路径了,只有域名或者ip+端口(可选)的情况下,会受location中路径部分的影响

server {
	listen        80;
	server_name  return.local;
    
	location /proxy {
		#代理地址末尾不带斜杠,nginx将会保留location中路径部分
		#如果访问:http://return.local/proxy.html
		#等于访问:http://i.9000.local/proxy.html
		proxy_pass http://i.9000.local;
		
		
		#代理地址末尾带斜杠,nginx将使用诸如alias的替换方式对URL进行替换,并且这种替换只是字面上的替换
		#如果访问:http://return.local/proxy.html
		#则 http://return.local/proxy 被替换成 http://i.9000.local/ 然后再加上.html部分,最后访问:http://i.9000.local/.html
		proxy_pass http://i.9000.local/;
	}
}

server {
	listen        80;
	server_name  return.local;
    
	location /proxy.html {
		#访问http://return.local/redirect.html,实际访问http://m.9000.local/
		proxy_pass http://m.9000.local/;
		
		#访问http://return.local/redirect.html,实际访问http://m.9000.local/proxy.html
		proxy_pass http://m.9000.local;
	}
}

代理地址后面有自己的路径的情况下,不受location中路径部分的影响

server {
	listen        80;
	server_name  return.local;
    
	location /redirect.html {
		#访问http://return.local/redirect.html直接代理到另外一个地址
		proxy_pass http://m.9000.local/index/api;
		
		#如果代理地址后面加了路径,则末尾不管是不是斜杠,都不会受location的路径的替换影响,因此,这2个写法是一样的效果
		proxy_pass http://m.9000.local/index/api/;
	}
}
相关推荐
大G哥3 小时前
记一次K8S 环境应用nginx stable-alpine 解析内部域名失败排查思路
运维·nginx·云原生·容器·kubernetes
妍妍的宝贝3 小时前
k8s 中微服务之 MetailLB 搭配 ingress-nginx 实现七层负载
nginx·微服务·kubernetes
叶北辰CHINA6 小时前
nginx反向代理,负载均衡,HTTP配置简述(说人话)
linux·运维·nginx·http·云原生·https·负载均衡
Lansonli8 小时前
云原生(四十八) | Nginx软件安装部署
nginx·云原生·ecs服务器
加油,旭杏14 小时前
【中间件学习】fastCG介绍和使用
学习·nginx·fastcgi
苹果醋317 小时前
大模型实战--FastChat一行代码实现部署和各个组件详解
java·运维·spring boot·mysql·nginx
tanxiaomi1 天前
vue 不是spa 单页面应用吗? 配置路由工作模式为history 后 ,为什么配置Nginx的 try_files 可以根据url 找到对应的文件?
前端·vue.js·nginx
twins35201 天前
配置Nginx以支持通过HTTPS回源到CDN
网络·nginx·https
astuv1 天前
在树莓派上部署开源监控系统 ZoneMinder
linux·nginx·树莓派·监控·摄像头·zoneminder·apache2
加油,旭杏2 天前
【中间件学习】Nginx快速入门(为了配置一个项目)
学习·nginx·中间件