Home : Internet : Server : Apache : Mod Rewrite : Moved Pages

Moving Pages with 301 Redirect

If you ever want to restructure your site, one of the biggest issue is the already established inlinks and search engine rankings. You do not want to lose those, under any circumstances, but this does not mean you cannot move your pages.

When a user requests a page, their browser sends the request to your server. Your server will return a status code - this status code is 200 for a normal page. You may have also heard of 404, used for a non-existant page. You can redirect your users with a 302 redirect - this is a temporarily moved page, or a 301 redirect - a permanently moved page.

Given the universal nature of this problem, we cannot give you a code to copy and paste and solve the problem. If you have not already done so, please read the tutorial.

This code should be placed in the htaccess file in the root of your domain, i.e. domain.com/.htaccess

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteBase /
   RewriteRule ^moved/page.html$ newlocation/page.html [R=301,L]
<
/IfModule>

The IfModule wrapper ensures we only execute this code if the mod_rewrite module is enabled. See portability notes for more information.

Inside the IfModule, the first four lines are discussed and explained in Start Rewriting (part one). All we are doing is ensuring we are ready to rewrite.

Then we have a simple RewriteRule that takes one page and redirects to another location, using the R=301 flag. For moving multiple pages, you may find a regex pattern more useful.

Example 2

You may wish to redirect pages depending on the QUERY STRING, for instance if you convert your forum to a new software. Let\'s assume your old topic view page was viewtopic.php?t=346 and the new page is showthread.php?tid=346. As mentioned in the tutorial, the query string is not passed to the RewriteRule so we must introduce a RewriteCond:

<IfModule mod_rewrite.c>
   Options +FollowSymLinks
   Options +Indexes
   RewriteEngine On
   RewriteBase /
   RewriteCond %{QUERY_STRING} t=([0-9]+)
   RewriteRule ^viewtopic.php$ showthread.php?tid=%1 [R=301,L,QSA]
<
/IfModule>

Note the use of the QSA flag so that we keep any additional GET parameters.

Subscribe to us on YouTube