How do I use mod_rewrite for common httpd URL rewriting use cases on Red Hat Enterprise Linux or Enterprise Web Server?
Posted 04/17/2009 - 10:10 by ds3721
Assumptions
Running Apache httpd 2.0.x or 2.2.x.
The Apache mod_rewrite module can be used to implement many common use cases. This document will provide working examples that can be modified to suit your configuration.
Examples
Example 1: Forwarding requests from the root context to a specific context (original URL preserved)
With the following mod_rewrite rule, the requested page will be rewritten to the subfolder context. The first RewriteCond checks to make sure that the request is not for the "context" folder (to prevent an infinite loop). Then the URL is rewritten under the "context" folder.
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/context/
RewriteRule ^/(.*) /context/$1 [PT]
For example, http://example.com/page.html is rewritten as http://example.com/context/page.html
Notes:
-
The Pass Through (PT) flag rewrites the URL without a 302 redirect response, thus preserving the URL on the client side.
-
The PT flag works within the same host:port. To pass through to another host:port requires using the Proxy (P) flag. However, the ProxyPass directive is typically used to do that, as ProxyPass is much faster than the rewrite P flag.
Example 2: Redirecting a request for a specific resource to another domain (original URL not preserved)
With the following mod_rewrite rule, the requested page will be rewritten to a different HTTP host, if the request is for "/page.html". The first RewriteCond checks to make sure the request is for example.com. Then the second rule checks to make sure the request is for "/page.html". If both match, then the URL is rewritten to devel.example.com.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{REQUEST_URI} ^/page.html$
RewriteRule ^/(.*) http://devel.example.com/$1 [R,L]
For example, http://example.com/page.html is rewritten as http://devel.example.com/page.html.
Notes:
-
There is an implicit AND between multiple RewriteCond statements.
Debugging
To debug mod_rewrite, enable rewrite logging. For example:
RewriteLog "logs/rewrite.log"
RewriteLogLevel
