Playing with mod_rewrite
What is mod_rewrite
mod_rewrite is a useful Apache module that allows for visible and invisible redirecting of websites. It can be used to create search engine and user friendly URL’s in place of complicated php URL’s, complete with variables. The rules can be placed in either the httpd.conf file or the local .htaccess file. Here’s an example file:
Allow Override all RewriteEngine on RewriteRule ^resources /index.php?option=com_content&view=article&id=172&Itemid=53 RewriteRule ^([a-zA-z0-9]+)$ /index.php
Here’s what we did:
If you would like to be able to put Rewrite rules within a particular directory, you must first allow .htaccess files to have rewrite rules. You can do this by having the following code in your httpd.conf file:
You can limit this in any way you would like. The above code would allow any directive to be included in the .htaccess file. You may wish to be more restrictive for security reasons.
Turn Rewrite engine on
In the directory where you would like the redirecting to take place, either create or edit your .htaccess file and add the following line:
In the .htaccess file, create a rewrite rule for each page you would like to redirect. You can use regular expressions if you have multiple similar pages to redirect. The basic rule has the following syntax:
RewriteRule ^MYLINK /index.php?myvar=myval or as an example RewriteRule ^resources /index.php?option=com_content&view=article&id=172&Itemid=53
The above example will create an invisible link, meaning that the user will only see yoursite/resources in the address bar, and not the fully resolved link. If you would like to have a visible link, because the site has permanently moved the page, then you can either include an [R] at the end of the line, or include the full path, starting with http in the link, instead of starting with the base directory, ie: RewritRule ^resources http://mydomain.com/index.php?option=com_content&view=article&id=172&Itemid=53 The above Rule will only be visible on newer versions of Apache.
Create Catch All Rule It might be useful to have a catch all rule to catch other “friendly” URL’s which cannot be properly resolved. The following rule will redirect any pages which aren’t resolved back to index.php
RewriteRule ^([a-zA-z0-9]+)$ /index.php
That’s all it takes. Happy Redirecting!