Skip to content

Instantly share code, notes, and snippets.

@pbuyle
Last active June 30, 2018 17:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbuyle/9792fcb36689bbf431a0f0c781d0e80a to your computer and use it in GitHub Desktop.
Save pbuyle/9792fcb36689bbf431a0f0c781d0e80a to your computer and use it in GitHub Desktop.
[Drupal] Redirects in settings.php with nikic/fast-route
{
...
"require": {
...
"nikic/fast-route": "^1.0"
...
}
...
}
<?php
include 'redirects.php';
<?php
$redirects = [
'something/{anything:.*}' => 'something-else/{anything}',
'another/one/{anything:.*}' => 'something/else/{anything}',
]
doDedirects($redirects);
/**
* Returns a HTTP 301 redirects and die on matching request.
*
* Match is done only on the request path (without the query string). Sources and their
* destinations can contains name pattern used to match muliple paths. For instance,
* use 'something/{anything:.*}' as source to match any path below `something/`. And
* use 'something/else/{anything}' as its destination to redirect to same path below
* 'something/else/`.
*
* @param $redirects
* Redirection rules as an associative array using source as key and destination as values.
*/
function doDedirects($redirects) {
// Collect redirects routes
$dispatcher = FastRoute\cachedDispatcher(function(FastRoute\RouteCollector $r) use ($redirects) {
foreach ($redirects as $source => $destination) {
$r->addRoute('GET', $source, $destination);
}
}, [
'cacheFile' => sys_get_temp_dir() . '/route.cache',
'cacheDisabled' => FALSE, /* optional, enabled by default */
]);
if (!empty($_SERVER['REQUEST_METHOD']) && !empty($_SERVER['REQUEST_URI'])) {
// Fetch method and URI (without the query string)
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// Match redirect rules and redirects if one is found.
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
if ($routeInfo[0] == FastRoute\Dispatcher::FOUND) {
$replace = [];
foreach ($routeInfo[2] as $key => $value) {
$replace["{{$key}}"] = $value;
}
$dest = strtr($routeInfo[1], $replace);
header("HTTP/1.1 301 Moved Permanently");
header("Location: $dest");
die();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment