Got a question?  Ask a developer in our Developer's Corner Forum

Back To The Developer's Corner Main Page

Useful htaccess Rewrite Examples

Apache has a wonderful way to change URLs on your server before they are processed.  To utilize this functionality, you first need to make sure mod_rewrite is enabled.

 

The next step is to modify your .htaccess file with the following to ensure that the RewriteEngine is turned on (this must come before any of the following code examples):

RewriteEngine On

 

This example will redirect the user and ensure that they are at http://www.cmsmarket.com/ rather than http://cmsmarket.com/

# Redirect to www
RewriteCond %{HTTP_HOST} ^cmsmarket.com [nc]
RewriteRule ^(.*) http://www.cmsmarket.com/$1 [r=301,nc,l]

 

This example will actually rewrite the URL so sitemap.xml goes to the XMap component:

# Sitemap.xml redirect
RewriteCond $1 ^sitemap.xml
RewriteRule ^(.*)$ /index.php?option=com_xmap&sitemap=1&view=xml&no_html=1 [L]

 

A couple notes about the syntax used above:

  • NC - This means no-case and says that the condition should not be case sensitive.
  • R=301 - This means to redirect rather than rewrite with an HTTP status of 301.
  • L - This means it is the last rule that should be processed.  Therefore, if this line is executed, everything else following in the .htaccess file will be skipped.
  • ^ - In a regular expression, this means the beginning of the line.
  • $ - In a regular expression, this means the end of the line.
  • (.*) - In a regular expression, .* means to match anything.  The () around the expression is so you can use the match later using varaibles like $1, $2, etc.

 

Apache has wonderful reference documents out there to help explain these:

http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond

http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteRule

 

If you are looking for some more advanced examples, we like this page:

http://corz.org/serv/tricks/htaccess2.php

 

 

Part of the SourceCoast Network:

SourceCoast / Cooking Allergy Free / CovertApps

© 2009 CMS Market. All rights reserved.

GTranslate Joomla Module