How to Avoid 404s and Redirect Old URLs in PHP

Share this article

Nothing can be said to be certain, except death and taxes. And URL changes.It’s often necessary to reorganize your site and change the URL structure but, assuming you have similar content, users should rarely encounter a “page not found” error. Producing unnecessary 404 pages is one of my top 10 development mistakes.In this article, we’ll create an automated PHP redirection system that converts old URLs to a new address. It’s not production code, but it will illustrate the basics so that you can adapt it for your own website.

1. Create a 404 error-handling file

If you’re yet to have a “not found” page, create a basic one named 404.php in the root of your website:
<?php// basic 404 error pageheader('HTTP/1.1 404 Not Found');header('Status: 404 Not Found');?><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Page not found</title></head><body><h1>Page not found</h1><p>Sorry, we cannot find that page.</p><p><a href="/">Please return to the home page&hellip;</a></p></body></html>
Note: What’s a 404?
404 is the HTTP error number returned when a resource is unable to be located on the server. The PHP code at the top of the above file returns this code to ensure systems such as search engines don’t mistake the page for real content.

2. Configure your server

You now need to tell your server that all 404 errors should be handled by the 404.php file. If you’re using Apache, add the following line to an .htaccess file in the root of your website:
errordocument 404 /404.php
For IIS, open the Internet Information Services Manager. In IIS7, double-click the “Error Pages” icon. (Users of previous versions must select the “Custom Errors” tab of the website properties.) Edit the 404 error code, choose a type of “URL”, and enter “/404.php” as the address.If you now visit a nonexistent page, such as, you should see the error page we created above.

3. Create the redirection system

We’ll place our redirection code in another file named redirect.php, to keep the functionality separate from the 404 content.Add the following code at the top of your 404.php file just after the <?php declaration:
Now create redirect.php in the website root and add the following code:
<?php// current address$oldurl = strtolower($_SERVER['REQUEST_URI']);// new redirect address$newurl = '';
The current page address is stored in $oldurl, e.g. /non-existent.url.We now need to examine that address and, if possible, translate it to a new URL (stored in the $newurl variable). How this is achieved will depend on the structure of your old and new URLs. For example, if the only change is that your ‘blog’ folder has been renamed ‘blogs,’ the following code could be sufficient:
$newurl = str_replace('blog', 'blogs', $oldurl);
You may be able to use a series of substitutions or regular expressions. Alternatively, a mapping of every old URL to its new address could be defined in an array or database table.If you have fairly simple redirect requirements, the following code could be used:
$redir = array(	'blog' => '/blogs/',	'video' => '/videos/',	'demo' => '/demonstrations/main/');while ((list($old, $new) = each($redir)) && !$newurl) {	if (strpos($oldurl, $old) !== false) $newurl = $new;}
The $redir array defines a number of value pairs that can be configured accordingly. If the first string can be found anywhere within the old URL, the redirection address is set to the second string. In the example above, if the word ‘blog’ is found in the missing page URL, the user will be redirected to ‘/blogs/’. If the old URL contains two or more of those words, the first one takes precedence; for example, /video/demonstrations would find ‘video’ first and redirect to ‘/videos/’.Once you have a $newurl value, you could optionally double-check that it exists before redirecting. Unfortunately, that poses a few risks:
  • The new URL may lack a physical file; for example, you’re using WordPress permalinks. PHP’s file_exists() function would fail to find anything.
  • You could use a function such as file() or http_get() to check that the URL exists; however, if it doesn’t, you’ll end up back at your redirect.php file–which could incur recursive redirect attempts.
Personally, I’d avoid double-checking the URL unless it’s easy to do so. If your redirect URLs are incorrect, it’ll soon become apparent during testing or by examining your server log files.Finally, if we have a $newurl, we’ll redirect to that page. Otherwise, we’ll show the 404.php error:
// redirectif ($newurl != '') {	header('HTTP/1.1 301 Moved Permanently');	header("Location: $newurl");	exit();}?>
This code is a simple example, but you should be able to adapt it for any situation. You could also consider further options such as:
  • logging all unmapped URLs to a file for later inspection
  • preventing multiple redirection mistakes by storing a cookie, using a session value, or passing an argument to the new URL
I hope you find it useful. I’ll show you how to modify the code for a WordPress installation in a new SitePoint article coming soon …

Frequently Asked Questions (FAQs) about Redirecting Old URLs in PHP

What is the purpose of redirecting old URLs in PHP?

Redirecting old URLs in PHP is a crucial aspect of website management and SEO. When a URL is changed or removed, any links to that URL will result in a 404 error, which can negatively impact the user experience and your site’s SEO ranking. By redirecting old URLs to new ones, you ensure that users and search engines find the correct page, thus maintaining your site’s usability and search engine ranking.

How can I redirect a 404 error to a custom page in PHP?

To redirect a 404 error to a custom page in PHP, you need to modify your .htaccess file. Add the following line: “ErrorDocument 404 /404.php”. This line tells the server to display the 404.php page whenever a 404 error occurs. Make sure your 404.php page is in the root directory of your website.

Can I redirect a 404 error to the homepage in PHP?

Yes, you can redirect a 404 error to the homepage in PHP. This can be done by modifying the .htaccess file and adding the line: “ErrorDocument 404 /index.php”. This will redirect all 404 errors to your site’s homepage.

How can I create a custom 404 error page in PHP?

Creating a custom 404 error page in PHP involves creating a new PHP file (e.g., 404.php) and designing it as per your requirements. Then, you need to add the following line to your .htaccess file: “ErrorDocument 404 /404.php”. This will display your custom 404 page whenever a 404 error occurs.

What is an HTTP 404 error?

An HTTP 404 error is a standard HTTP status code that indicates that the client was able to communicate with the server, but the server could not find the requested file or page. This error often occurs when a webpage has been removed or moved to a different URL.

How can I handle 404 errors in PHP?

Handling 404 errors in PHP can be done by using the .htaccess file to redirect users to a custom error page or the homepage. This improves the user experience and helps maintain your site’s SEO ranking.

Can I use PHP to redirect URLs?

Yes, PHP can be used to redirect URLs. The header() function in PHP can be used to send a raw HTTP header to the client. For example, to redirect a user to a new page, you can use the following code: header(“Location: newpage.php”); exit;

What is the .htaccess file?

The .htaccess file is a configuration file used by Apache-based web servers. It allows you to control various server settings, including URL redirection, password protection, and error responses, on a per-directory basis.

How can I test if my URL redirection is working?

You can test if your URL redirection is working by trying to access the old URL. If the redirection is set up correctly, you should be automatically redirected to the new URL or the specified error page.

Can URL redirection affect my website’s SEO?

Yes, URL redirection can affect your website’s SEO. If done correctly, it can help maintain your site’s search engine ranking when URLs are changed or removed. However, improper redirection can result in broken links and 404 errors, which can negatively impact your site’s SEO.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week