Skip to content

Instantly share code, notes, and snippets.

@amomin
Last active December 5, 2015 01:19
Show Gist options
  • Save amomin/790273e9b3ee4313ca6a to your computer and use it in GitHub Desktop.
Save amomin/790273e9b3ee4313ca6a to your computer and use it in GitHub Desktop.
Conditional 302 redirect

Conditional redirect based on use case from work.

Page a.php is moving to b.php, and b.php is not yet ready, but for some reason (well, we'll assume there is a reason) it is necessary to direct users to b.php to tell them that the new content will be hosted there, and then send them back to the original content at a.php without redirecting them again to b.php.

This is one way to do it in php. We introduce a query string parameter on the request to a.php that - if present - will force the content to load with 200 response; otherwise it 302 redirects to b.php. When b.php is completely ready it will be turned into a permanent 301 redirect.

(In reality a.php and b.php live on different domains but this example adapts easily to that case - and you could replace the query string condition with something else, like a referal domain check or other.)

<?php
if ($_GET['nordir'] == 1) {
http_response_code(200);
} else {
http_response_code(302);
header('Location: b.php');
exit;
}
?>
<p> I am the content you want to see </p>
<p> Message you have to be made to see. </p>
<a href="a.php?noredir=1"> Back to the content you actually want. </a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment