Apache mod rewrite

From ALSwiki
Jump to: navigation, search

I had an older non-joomla which had built up many inbound links at other sites. Once converted to joomla, the page views dropped by about 80%. Watching the logs was painful as people came in on links that resulted in 404 errors. Here's what I did.

Enable Joomla's Search Engine Friendly URLs

From the admin interface:

 Site >> Global Configuration

Under SEO Settings, set "Search Engine Friendly URLs" to "yes". All URLs will now have a form something like:

 <your site name>/index.php/<section-name>/<category id>-<category-name>/<article id>-<article-name>

Special characters and spaces will be converted to legal characters. e.g. '"' becomes "q" and " " becomes "_". On my ourmexico.com site, the article "The Monarchs of Morelia" in the the "Travel" category of section "Stories" now has a url:


Add the redirection rules

These can go in an .htaccess file or in the Apache config file. There are many resources out there that provide instructions and examples.

Most of these assume you are trying to take an incoming "friendly URL" like /pies/apple/ and turn it into something like pies.php?type=apple. I had the opposite problem. My old site used "unfriendly urls" like "story.php?storyID=25". Apache stores the "story.php" as the request uri and the storyID=25 as the query string.

RewriteCond to the rescue!

RewriteCond allows you to set a series of conditions that must be true before the rewrite rule runs. I needed to test both the request uri and the query string. Here's a rule, that runs if the request uri is "story.php" and then checks to see if the query string contains the substring "20". In my case I didn't need a more complex regular expression, but could have easily applied one in the test. The R=301 sends a "Moved Permanently" code and the L says this is the last rule that should run if it matched.

 RewriteCond %{REQUEST_URI} ^.*story\.php$ 
 RewriteCond %{QUERY_STRING} 20
 RewriteRule ^.*$ /index.php/stories/34-travel/99-sierra-gorda-missions? [R=301,L]