How To Re-Direct Old URLs to New URLs

When transferring your old website to a new one, you will probably want to re-direct your visitors so that links pointing to outdated URLs are sent to the correct new ones.

The Javascript window.location

The page that gets loaded into a browser is governed by the JavaScript property window.location.

Setting the window.location parameter equal to a new URL, will force the current webpage to the new one that is specified.

For example, if you wanted to redirect all your visitors to www.google.com when they arrived at your site, you would just use the script below:

<script type="text/javascript">
<!--
window.location = "http://www.google.com/"
//-->
</script>

This would re-direct user to the Google home page no matter what specific old web page they clicked on.

However, re-directing your viewers to some generic homepage is probably not the best. They may have bookmarked favorite sections of your old website and may end up lost, especially if your site has hundreds of web pages.

To re-direct a specific web pages it may be better to make use of the location.href property, used to return the entire URL of the current page, and the location.replace function to replace the current web page with a new one.

Example: re-directing old Blogspot pages

If you have blog postings at Blogger.com and have imported/copied them to a new site, such as WordPress, then you might wish to do some re-direction.

For example, when using Blogger, all javascript modifications take place in the Templates tab within the subsection called “Edit HTML”.  Underneath <script type=’text/javascript’> is where you make any new modifications:

As a very simple example, say you wanted to re-direct an old we page called “http://andyuk2010.blogspot.com/2010/04/using-boost-libraries-in-visual-studio.html” to its new home at “http://technical-recipes.com/?cat=18” the the following simple code should achieve this:

if ( location.href == "http://andyuk2010.blogspot.com/2010/04/using-boost-libraries-in-visual-studio.html" )
{
    location.replace( 'http://technical-recipes.com/?cat=18' );
}

And add as many additional clauses as you like using additional else..if statements.

`