Given the power and flexibility of mod_rewrite it's not surprising that people often use it as their golden hammer. Part of gaining knowledge about mod_rewrite is knowing when not to use it.
The following is a list of misuses of mod_rewrite and more appropriate (and often faster) alternatives. These examples assume the RewriteRules
are not placed in a directory context (i.e., not in a .htaccess
file nor in a <Directory>
section).
Simple Redirects
No Format |
---|
RewriteRule ^/(.*) http://other.example.com/$1
# is better expressed as..
Redirect / http://other.example.com/
|
Complex Redirects
No Format |
---|
# redirect and drop the trailing uri
RewriteRule ^/.* http://other.example.com/
# is better expressed as.. (we only need to match every possible string
# without storing it, thus just ^)
RedirectMatch ^ http://other.example.com/
|
No Format |
---|
# redirect to a uri containing a portion of the original
RewriteRule ^/foo/(.+)/bar http://other.example.com/$1
# is better expressed as..
RedirectMatch ^/foo/(.+)/bar http://other.example.com/$1
|
Appropriate uses of mod_rewrite for redirecting include:
- Redirecting based on the query string
- Redirecting based on other request details such as user-agent.
Aliasing
No Format |
---|
RewriteRule ^/foo/(.*) /bar/$1
# is better expressed as..
Alias /foo /var/www/bar
|
or
No Format |
---|
RewriteRule ^/foo/(.*)/baz /bar/$1
# is better expressed as..
AliasMatch /foo/(.*)/baz /var/www/bar/$1
|
Appropriate uses of mod_rewrite for aliasing include:
- Aliasing based on complex rules
TODO, validate AliasMatch example, add more valid uses or expand them
Proxying
No Format |
---|
RewriteRule ^/(.*) http://other.example.com/$1 [P]
# is better expressed as..
ProxyPass / http://other.example.com/
|
No Format |
---|
# reverse proxy everything except images
RewriteCond %{REQUEST_URI} !^/images
RewriteRule ^/(.*) http://other.example.com/$1 [P]
# is better expressed as..
ProxyPass /images !
ProxyPass / http://other.example.com/
|