Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Last active January 11, 2016 16:23
Show Gist options
  • Save jordanmaslyn/d9d80f53b1fd255e55cb to your computer and use it in GitHub Desktop.
Save jordanmaslyn/d9d80f53b1fd255e55cb to your computer and use it in GitHub Desktop.
PHP Redirects to emulate .htaccess redirects on nginx
<?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
}
?>
@fyaconiello
Copy link

this is untested, and im not sure of actual impact, but if the redirects array gets huge (several several hundred) you may need to recover some of that memory if a match isn't made (non-redirect).

<?php
// allow us to force GC
gc_enable(); // PHP >= 5.3.0
....
if (array_key_exists($base_uri, $rewrite_paths)) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: '.$rewrite_paths[$base_uri]);
    exit();
}

// no match so free the array from mem and force a garbage collect
unset($rewrite_paths);
gc_collect_cycles(); // PHP >= 5.3.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment