nginx下的proxy_pass使用

发布时间 2023-12-21 11:56:39作者: 第一夫人

之前的文章说到了,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/;
	}
}