It is not unusual that a website’s links structure would be broken perhaps because of file name change or file deletion. Even with well structured WordPress powered websites, this problem would sometimes crop up. These instances would pose a problem especially for Search Engines and the ranking of your website. The 301 redirect is a solution to this.
When a browser or a search engine crawling your website happens to see a none existing link, the server is going to respond with an HTTP status 404 – and that is one of the worst thing somebody or a bot viewing your website would see. “Where’s that page? Ah, this website sucks!”, one would say and that would discourage them from going to your most relevant pages.
It is explicitly suggested in Google’s Search Engine Starter Guide that a 301 Redirect could be a viable solution to this. A 404 returns a blank page to the user but a 301 redirect would lead the user to another page. So, for SEO purposes, the 301 redirect returns a page as if the page exists.
There is a way in WordPress to prevent sending a blank page to the user or bot. WordPress does it by giving template designers the option of having a 404.php in the template. So instead of being led to a blank page, the 404.php will show. But not all websites are made out of WordPress. 🙁
So, how is a 301 redirect implemented in PHP? It is very simple. Lets just return a header to the browser or bot with the following code snippet:
The above code tells the browser that the link is removed and that the user is to be redirected. The code above does the same thing to the search engine, so the search engine realizes that the website doesn’t have broken links.
The webmaster is then going to save this as a file (perhaps 404.php) and let it be the file to display when a 404 is reached. This is done in the webhost’s admin panel (cpanel, etc.).
It is common also to see 404.php files in templates use the above code snippet. The usual redirection is to the root page of the wordpress website.