使用 PHP 测试 301 重定向
我总是写一些脚本来测试一下,我想我会开始记录它们,以防我将来需要它们。这是一个小脚本,它将遍历文本文件的内容并验证一堆301重定向是否指向它们要指向的位置。此脚本假定重定向已在服务器上就位,但这是我正在测试的内容。这里是重定向文本文件的格式。
http://www.exmaple.com/old_page http://www.exmaple.com/new_page http://www.exmaple.com/nother_old_page http://www.exmaple.com/another_new_page
下面的脚本加载到这个文件中,并使用PHP函数循环遍历它,get_headers()以测试第一个URL是否重定向到第二个。如果发现任何问题,则报告行号和问题。
$line) { $line = explode(' ', trim($line)); $headers = @get_headers($line[0], 1); if ($headers === FALSE) { echo "Line " . ($line_num + 1) . ": Malformed URL found!\n"; } else if (!isset($headers['Location'])) { echo "Line " . ($line_num + 1) . ": " . $line[0] . " does not redirect to " . $line[1] . "\n"; } else if (isset($headers['Location']) && $headers['Location'] != $line[1]) { echo "Line " . ($line_num + 1) . ": " . $line[0] . " redirects to " . $headers['Location'] . " and not " . $line[1] . "\n"; } } echo "Finished redirect test.\n";
使用上面的示例是一个好主意,因为它演示了如果发现问题会发生什么。这是输出:
Line 1: http://www.exmaple.com/old_page does not redirect to http://www.exmaple.com/new_page Line 2: http://www.exmaple.com/nother_old_page does not redirect to http://www.exmaple.com/another_new_page Finished redirect test.