redirect.php 1.21 KB
Newer Older
S. Zeid's avatar
S. Zeid committed
1 2
<?php

3 4 5 6 7
$request_uri = $_SERVER["REQUEST_URI"];
function redirect($to) {
 header("Location: $to");
}

8 9
$redirects_text = file_get_contents("_redirects");
$redirects_text = preg_replace('/\s+[-=]>\s+/', ' => ', $redirects_text);
10
$redirects_text = str_replace("\r", "\n", str_replace("\r\n", "\n", $redirects_text));
11 12 13 14 15 16 17
$redirect_lines = explode("\n", $redirects_text);

$redirects = array();
foreach ($redirect_lines as $line) {
 if (strpos($line, "#") !== 0) {
  $parts = explode(" => ", $line, 2);
  if (!empty($parts[0]) && !empty($parts[1]))
18
   $redirects[rtrim($parts[0], "/")] = $parts[1];
19 20
 }
}
S. Zeid's avatar
S. Zeid committed
21 22

foreach ($redirects as $old => $new) {
23 24 25 26 27 28 29 30 31
 if (strlen($old) >= 2 && substr($old, strlen($old) - 2) === "/*" &&
     (strpos($request_uri, substr($old, 0, strlen($old) - 1)) === 0 ||
      $request_uri == substr($old, 0, strlen($old) - 2))) {
  redirect(rtrim($new, "/") . substr($request_uri, strlen($old) - 2));
  exit();
 }
 if ($request_uri == $old ||
     $request_uri == $old."/") {
  redirect($new);
S. Zeid's avatar
S. Zeid committed
32 33 34 35
  exit();
 }
}

36
if ($request_uri != $_SERVER["SCRIPT_NAME"]) {
S. Zeid's avatar
S. Zeid committed
37 38 39 40 41 42 43 44 45 46 47
 header("HTTP/1.0 404 Not Found");
 if (file_exists("404.html"))
  readfile("404.html");
 else
  echo "<h1>404 Not Found</h1>";
} else {
 highlight_file(__FILE__);
 exit();
}

?>