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/;
	}
}
相关推荐
null_null99910 小时前
宝塔nginx http转https代理
nginx·http·https
Freed&1 天前
《Nginx进阶实战:反向代理、负载均衡、缓存优化与Keepalived高可用》
nginx·缓存·负载均衡
Hover_Z_快跑1 天前
Docker 部署 Elasticsearch 8.12 + Kibana + Nginx 负载均衡
nginx·elasticsearch·docker
huazeci1 天前
deepin Ubuntu/Debian系统 环境下安装nginx,php,mysql,手动安装,配置自己的项目
nginx·ubuntu·debian
就叫飞六吧2 天前
Nginx 主要的几种负载均衡模式
运维·nginx·负载均衡
脚踏实地的大梦想家3 天前
【Docker】P2 Docker 命令:从Nginx部署到镜像分享的全流程指南
java·nginx·docker
苹果醋34 天前
element-ui源码阅读-样式
java·运维·spring boot·mysql·nginx
向上的车轮4 天前
Actix Web 不是 Nginx:解析 Rust 应用服务器与传统 Web 服务器的本质区别
前端·nginx·rust·tomcat·appche
摇滚侠5 天前
Nginx 与 F5 负载均衡的区别
nginx·负载均衡
huangql5205 天前
Nginx 从零到精通 - 最详细的循序渐进教程
开发语言·网络·nginx