Skip to content

Instantly share code, notes, and snippets.

@romaricpascal
Created February 26, 2020 17:26
Show Gist options
  • Save romaricpascal/8ddccda0d90f00ccb618eb13816b3869 to your computer and use it in GitHub Desktop.
Save romaricpascal/8ddccda0d90f00ccb618eb13816b3869 to your computer and use it in GitHub Desktop.
4042302 in PHP
<?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;
}

4042302 in PHP

Implementation of the 4042302 concept in PHP, to be set up as an ErrorDocument on Apache for example. It adds a HEAD request to the fallback server to check if it would serve the requested path. This allows to differenciate legacy requests from actual 404 and serve the most appropriate content:

  • fallback to a subdomain for the former,
  • custom 404 page for the later
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment