PHP, Wordpress

Writing a 301 redirect script in PHP or redirect with .htaccess

Search engine traffic is important to any website and when you once in a while wants to reorganize your website the existing link structure might be impacted.

This is where 301 redirects come in handy. They will redirect incoming traffic to the old urls to the new ones so that search engine traffic and traffic from old links will not be lost. Redirecting with 301 links will also ensure you will not be penalized for redirecting links.

One way is to use your .htaccess file and hardcode the links

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
Redirect 301 /oldcontent/page1.html /2002/07/page1/?
</IfModule>

If you have query strings it’s a bit more tricky with .htaccess, but it can be hardcoded in .htaccess like this

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^old_content_query_part$
RewriteRule ^old.php$ /2002/07/new_slug/? [L,R=301]
</IfModule>

A more dynamic solution is to use a php script. By doing so you can customize it however you want and make it extremely flexible to do redirects for many old links with one small script.

//Typically you have a php script with parameters and you catch them in the beginning. This could also be a the basis for a query to do a database lookup so that you can dynamically create a WordPress url with year / month / slug
$id = $_GET["id"];

// possible dblookup to geth year and month for the old post, depending on your new url structure.

$sRedir = '/year/month/'. $id;

header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$sRedir);

With a very old website that has evolved over almost 20 years I’ve used all these methods over the years, but as long as the original content is database based creating a php script is definitely the most easy way to do this efficiently.

 

Leave a Comment

Your email address will not be published. Required fields are marked *