php PHP重定向以在nginx上模拟.htaccess重定向

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php PHP重定向以在nginx上模拟.htaccess重定向相关的知识,希望对你有一定的参考价值。

<?php

// include this file in your root index.php before any Wordpress files start getting pulled in.

// allow us to force garbage collection (for performance)
// commented out for now because it should be enabled by default. Going to test without it first.
// gc_enable(); // PHP >= 5.3.0

// old_path => new_path
// make sure all of your old_paths have no trailing slash
$rewrite_paths = array(
  "/old/path-1" => "/new-path1/",
  "/another-old-path" => "/new-paths-are-better",
  "/this/is/an/example/of-an-old-path" => "/our/new/path"
);

/**
 * The code below should not need to be altered. You should only modify the array above.
 *
 * The code below does the following:
 *
 * 1. Remove any GET parameters from the requested URI (makes matching more consistent, but needs to be removed in case you need to match old queries).
 * 2. Check for a trailing slash on the requested URI and remove it if found.
 * 3. Check for the base of the requested URI (minus GET params and trailing slash) and look for that key in the array above.
 * 4. If the requested URI is found as a key, 301 Redirect to the respective value (new URL)
 */

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$base_uri = $uri_parts[0];

// In case you need to match query parameters in the original URLs, comment out the two lines above and uncomment the line below:
// $base_uri = $_SERVER['REQUEST_URI'];

if(substr($base_uri, -1) == '/') {
  // trim trailing slash
  $base_uri = substr($base_uri, 0, -1);
}

if (array_key_exists($base_uri, $rewrite_paths)) {
  header('HTTP/1.0 301 Moved Permanently');
  header('Location: '.$rewrite_paths[$base_uri]);
  exit();
} else {
  // no match so free the array from mem and force a garbage collect
  unset($rewrite_paths);
  gc_collect_cycles(); // PHP >= 5.3.0
}

?>

以上是关于php PHP重定向以在nginx上模拟.htaccess重定向的主要内容,如果未能解决你的问题,请参考以下文章

php 过滤以在提交或重定向时从URL中删除联系表单7查询字符串。进入函数文件。

wordpress重定向及nginx配置

Lumen + nginx = 错误 500,重写或内部重定向循环,同时内部重定向到“/index.php”

nginx虚拟目录配置+重定向

nginx 重定向循环,从 url 中删除 index.php

text nginx重定向循环,从url中删除index.php