|
<?php |
|
|
|
// Ideally read those 4 settings from environment variables |
|
// with `getenv` to make the script more portable. Only one |
|
// of the `$error_...` needs to have a value. |
|
|
|
// The base_url to which the path will be appended |
|
// when checking for a fallback. No trailing slash. |
|
$base_url = "https://example.com"; |
|
// A URL to redirect to if the fallback didn't serve the page |
|
$error_redirect = ''; |
|
// or a document to `include` |
|
$error_document = ''; |
|
// or just a text message to `echo` |
|
$error_message = 'Not found'; |
|
|
|
// If a base_url is set check if it hosts the page |
|
// and redirect if it does |
|
if (!empty($base_url)) { |
|
$url = "$base_url$_SERVER[REQUEST_URI]"; |
|
$ch = curl_init($url); |
|
curl_setopt($ch, CURLOPT_NOBODY, true); |
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); |
|
$response = curl_exec($ch); |
|
$response_code = curl_getinfo($ch,CURLINFO_RESPONSE_CODE); |
|
curl_close($ch); |
|
|
|
if ($response_code >= 200 && $response_code < 300) { |
|
header("Location: $url", true, 302); |
|
die(); |
|
} |
|
} |
|
|
|
// If we reached here, it means we either didn't have |
|
// a base_url set or the base_url didn't host the page |
|
// so we 404 ourselves. We'll use a similar pattern as |
|
// Apache ErrorDocument and either redirect, include |
|
// a specific script or display a message |
|
if (!empty($error_redirect)) { |
|
header("Location: $error_redirect", true, 302); |
|
die(); |
|
} else if (!empty($error_document)) { |
|
include($error_document); |
|
} else { |
|
echo $error_message; |
|
} |