How to rewrite URLs in Apache with the mod_rewrite module

This article is an introduction to URL rewrites using Apache's mod_rewrite module.

Using the mod_rewrite module

Apache's mod_rewrite module enables you to rewrite URLs. You can use URL rewrites in a number of scenarios, including:

  • Providing cleaner, more readable links to your web site. For example, instead of the URL http://www.example.com/products.php?id=232&cat=11, you could use the URL http://www.example.com/products/calculator instead with rewrites. In addition to making URLs more human-readable, they are also more search engine friendly, and can improve a web site's ranking and searchability.
  • Hiding the web site's internal implementation. Using the previous URL example, we can hide the fact that the site is using PHP, as well as mask queries that attackers could potentially use for malicious purposes.

To specify URL rewrite rules, you use directives such as RewriteRule and RewriteCond in an .htaccess file. These directives rely heavily on regular expressions to provide URL pattern matching. There are many mod_rewrite options available, and describing all of them is beyond the scope of this article. However, here is an example of a URL rewrite using the mod_rewrite module:

RewriteEngine on
RewriteRule ^products/calculator$ /products.php?id=232&cat=11

In this example, visitors who use the URL products/calculators will actually view products.php?id=232&cat=11, though they will be unaware of this (the location bar in their browser still displays /products/calculators). The RewriteEngine directive simply enables or disables URL rewriting, while the RewriteRule directive does the actual work of matching an incoming URL and specifying the target URL.

For more examples of the mod_rewrite module in action, please see these articles:

More Information

For more information about how to use the mod_rewrite module, please visit http://httpd.apache.org/docs/current/mod/mod_rewrite.html.

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.