2.8. Making URLs Easy to Find and Remember
Problem
You need to turn complex content management system, blog, or shopping cart URLs into easy-to-remember URLs.
Solution
Use mod_rewrite
rules in an
.htaccess file to invisibly turn simple URLs into
complex query strings that return dynamic pages to the visitor's
browser. For example, an e-commerce site that sells men and women's
clothes might offer a variety of men's shoes, such as boots, oxfords,
sandals, and loafers.
A URL for the list of loafers might look like this:
http://mensandwomensclothes.com/store/list.php?type=mens&cat=shoes&subcat=loafers |
Using rewrite rules, you can tidy up the URL to something like this:
http://mensandwomensclothes.com/store/mens/shoes/loafers/ |
A rewrite rule in the .htaccess file that you create or modify in the /store directory takes care of converting the clean URL to the more complex query string that the store template (list.php) needs to generate the list of loafers from the store database. Here's the code for the rewrite rule:
RewriteEngine On Options +FollowSymLinks RewriteRule ^(.*)/(.*)/(.*)/$ /store/list.php?type=$1&cat=$2&subcat=$3
Assuming the mod_rewrite
module has been compiled into your installation of Apache (typically,
it has), the first line (RewriteEngine
On
) prepares the module for the rewrite rule or rules to
follow. The second line (Options
+FollowSymLinks
) can be left out if it's already in the main
Apache configuration file (typically,
httpd.conf).
The third line contains the rule. Three ...
Get Web Site Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.