Sysadmins of the North
Don't forget to share this post!

Redirect old URL to new URL or send 404 page with PHP

Redirect pages with PHP. If you’ve moved some old PHP pages, or URLs, to new pages and URLs, you can use the following PHP code snippet to easily redirect all visitors and incoming requests to the new location. This PHP code snippet uses a 301 Moved Permanently redirect, perfect for SEO.

Redirect pages with PHP: redirect old URLs to new URLs

Save the following PHP code as 404.php and set this PHP page as your custom default 404 Not Found page. This will prevent visitors from getting ugly and unwanted default 404 Page Not Found messages.

// watch out for accepting request_uri input without validation/sanitation!
$arrMoved=array("/php/guestbook/" => "/php/phpGuestbook/",
	        "/php/forumzz.php" => "/php/forum.php",
	        "/old.php" => "/new.php",
	        "/..." => "/...");
if(array_key_exists($request,$arrMoved)) {
  header("HTTP/1.0 301 Moved Permanently");
  header("Location: $newplace");
  header("Connection: close");
  exit(); // ALWAYS use exit() after header()
else {
  header("HTTP/1.0 404 Not Found");

Your normal HTML code goes here, if a match is found the 
visitor will have been redirected. Only genuine 404 errors will see the HTML below.

 Follow me on Twitter: @HertogJanR
       404 Error page
    <p>Sorry but this page cannot be found.</p>

buy me a coffee
Buy Me A Coffee

About the Author Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, WordPress, websites & optimization. Want to support me and donate? Use this link:

follow me on:

Leave a Comment:

Skip to content