allow_redirects

摘要

描述请求的重定向行为

类型

  • bool
  • array

默认值

1. [
2. 'max'             => 5,
3. 'strict'          => false,
4. 'referer'         => true,
5. 'protocols'       => ['http', 'https'],
6. 'track_redirects' => false
7. ]

常量

GuzzleHttp\RequestOptions::ALLOW_REDIRECTS

设置成 false 禁用重定向。

1. $res = $client->request('GET', '/redirect/3', ['allow_redirects' => false]);
2. echo $res->getStatusCode();
3. // 302

设置成 true (默认设置) 来启用默认最大次数为5的重定向。

1. $res = $client->request('GET', '/redirect/3');
2. echo $res->getStatusCode();
3. // 200

你也可以传送一个包含了以下键值对的关联数组:

  • max: (int, 默认为5) 允许重定向次数的最大值。
  • strict: (bool, 默认为false) 设置成 true 使用严格模式重定向 严格RFC模式重定向表示使用POST请求重定向POST请求 vs 大部分浏览器使用GET请求重定向POST请求。
  • referer: (bool, 默认为true) 设置成 false 重定向时禁止添加Refer头信息。
  • protocols: (array, 默认为[‘http’, ‘https’]) 指定允许重定向的协议。
  • on_redirect: (callable) 发生重定向时调用PHP回调,包含了原始的请求以及接收到重定向的响应,on_redirect的任何返回将会被忽略。
  • track_redirects: (bool) 当设置成 true 时,每个重定向的URI将会按序被跟踪头信息 X-Guzzle-Redirect-History 。
1. use Psr\Http\Message\RequestInterface;
2. use Psr\Http\Message\ResponseInterface;
3. use Psr\Http\Message\UriInterface;

5. $onRedirect = function(
6. RequestInterface $request,
7. ResponseInterface $response,
8. UriInterface $uri
9. ) {
10. echo 'Redirecting! ' . $request->getUri() . ' to ' . $uri . "\n";
11. };

13. $res = $client->request('GET', '/redirect/3', [
14. 'allow_redirects' => [
15. 'max'             => 10,        // allow at most 10 redirects.
16. 'strict'          => true,      // use "strict" RFC compliant redirects.
17. 'referer'         => true,      // add a Referer header
18. 'protocols'       => ['https'], // only allow https URLs
19. 'on_redirect'     => $onRedirect,
20. 'track_redirects' => true
21. ]
22. ]);

24. echo $res->getStatusCode();
25. // 200

27. echo $res->getHeaderLine('X-Guzzle-Redirect-History');
28. // http://first-redirect, http://second-redirect, etc...