Tuesday, 3 November 2015

Webpage redirection

What happens if your visitors try to access a page that was recently renamed, deleted, or moved? By default they will get an error message, but you can change that. Instead of your visitors stumbling upon an error when trying to access such a page, you can set a redirection rule that will redirect them to a new page.

This page is about individual page redirection. For information on domain redirection check out our domain redirection tutorial.

NOTE: Redirection is very good for search engines. Search engines need to know when one of your files has changed locations to re-index your site properly.

301 and 302 redirects

There are two types of redirects - 301 and 302. These are actually HTTP status codes which specify the status of communication between the web browser and the web server.

The code samples below should be placed in the file you're redirecting from unless otherwise specified.

302 redirects

302 redirects are used when a page's location has been changed temporarily.

HTML

HTML 302 redirects work through the <meta> tag:

<meta http-equiv="refresh" content="10; url=http://www.site.com/newpage.html" />

In the content attribute, the number is the amount of seconds before redirecting to the new page specified by url.

Javascript

Javascript 302 redirects work through the window.location property:

<script type="text/javascript">
window.location="http://www.yahoo.com";
</script>

Set the window.location property equal to the URL you want to redirect to. Include this Javascript code in the head section of an HTML document. The redirect should occur right away.

PHP

PHP 302 redirects work through the header function:

<?php header("Location: http://www.site.com/newpage.html"); ?>

Inside the header() function, put Location: followed by the URL to redirect to.

.htaccess

Put this in your .htaccess file:

redirect 302 /oldfile.html http://www.yoursite.com/newfile.html

/oldfile.html is the location of the file you're redirecting from and http://www.yoursite.com/newfile.html is the location of the file you're redirecting to.

301 redirects

301 redirects are used when a page's location has been changed permanently.

PHP

PHP redirects are 302 redirects by default, but by putting the HTTP/1.1 301 code at the top, we create a PHP 301 redirect:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.site.com/newpage.html");
?>


NOTE: When you use a PHP redirect make sure that the redirect code is the only thing on the page that you are redirecting from.

.htaccess

Put this in your .htaccess file:

redirect 301 /oldfile.html http://www.yoursite.com/newfile.html

/oldfile.html is the location of the file you're redirecting from and http://www.yoursite.com/newfile.html is the location of the file you're redirecting to.

No comments:

Post a Comment