nginx下的return,rewrite重定向功能使用场景

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

nginx下的return,rewrite虽然好用,而且功能强大,但是也有它的局限,我们一起来看看

return和rewrite都可以实现重定向的功能,但是不同的场景下,它们的表现是不一样的,直接上列子:

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

$a = file_get_contents("http://return.local/redirect?a=1&b=2");
echo $a;

http://return.local的nginx配置如下

server {
	listen        80;
	server_name  return.local;
    
	location /redirect {
		#return 302 http://m.9000.local/index/api?$args;//return模式
		#rewrite ^(.*)$ http://m.9000.local/index/api?$args permanent;//rewrite模式
	}
}

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

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

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

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

使用return和rewrite,执行效果如下,结果一样的

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

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

 http://return.local的nginx配置和http://m.9000.local/index/api执行代码和步骤1一样

使用return和rewrite,执行效果如下

哦豁,return的返回302,rewrite的返回301,那就说明http://m.9000.local/index/api这个地址没有成功执行,在这之前就已经报错了

总结

1、return,rewrite重定向只支持在浏览器,postman,或者php里面的file_get_contents,等其他支持http status变化的工具中使用(可能这边描述不太准确,明白意思就可以了)

2、如果是客户端,例如app客户端,游戏客户端,或者curl请求的话,则不能使用