301 redirect using regular expressions

Depending on how the Apache installation is configured, htaccess files may or may not work to do 301 redirects. The mod_rewrite module must be loaded and enabled to use the following techniques to perform a 301 redirect.

Open your current .htaccess file or create a new file called ".htaccess". The naming of this file is important, you must include the leading period.

The following data is an example of a 301 redirect done using a RewriteRule.

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} id=([0-9]+)
RewriteRule ^page\.php$ http://www.mysite.ca/page%1.html? [R=301,L]

The first line simple turns on the RewriteEngine so you can use the rewrite rules which follow. The second line sets the base folder which we are refering to in these rules. If you were creating rules for files in a subfolder you would change the RewriteBase to the subfolder name.

With a normal RewriteRule, you can not match information in the query string, and therefore you must use the RewriteCond to match the query string. As you can see in the example, we are matching an ID number in the query string. The data extracted using the regular expression in the RewriteCond is substituted into the rewritten URL using the %1. If you wish to match and extract data in the RewriteRule, you would use $1 in the destination URL.

The parameters after the RewriteRule ([R=301,L]) mean that we wish to do a 301 redirect and to stop processing rules once this is matched.

The goal of this TechByte was to give a basic example of doing regular expression matching in a query string using mod_rewrite. The mod_rewrite capabilities are extremely powerful and complex and if you wish to learn more about them, try this site:

Apache mod_rewrite documentation

Let us know if you have any other input on ways to do this!


Author: DPAK
Created: Nov 3 2005 (last modified Nov 28 2005)
Categories: Apache
TechByte #78

Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.



Add a comment about this TechByte

If you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED.

Posted By: (Optional)

Comments:


Other TechBytes: