Forum Topic: Best way to redirect?

Forum: .htaccess Forum : Redirecting • Posted by 0racle • Updated:

I’ve been reading through the book and have a question about which method is best for redirecting stuff. I like the simplicity of Redirect and RedirectMatch, but for conditional requests RewriteCond and RewriteRule are required. Is one better than the other in terms of performance (or otherwise), or is whatever works?

2 Replies to “Best way to redirect?”

Posted by Jeff Starr

mod_alias requires fewer CPU cycles than does mod_rewrite, but that shouldn’t stop you from using either method in most cases. Optimized code is also important. For example, instead of using multiple Redirect directives like this:

RedirectMatch /path/to/file/ http://example.com/
RedirectMatch /path/to/files/ http://example.com/
RedirectMatch /path/to/more-files/ http://example.com/

Combine them into a single directive:

RedirectMatch /path/to/(file|files|more-files)/ http://example.com/

And similarly there are ways of consolidating disparate Redirect directives using RewriteCond and RewriteRule, enabling cleaner code and more efficient processing.

In general, use Redirect/RedirectMatch when possible; otherwise use RewriteCond/RewriteRule.

Posted by eet

There are some important differences between mod_alias (ie, Redirect/RedirectMatch) and mod_rewrite (ie, RewriteCond/ RewriteRule):

  • mod_rewrite can do everything, mod_alias only some things
  • mod_rewrite involves mapping and is executed before mod_alias
  • mod_alias generally requires less data and processing
  • mod_alias matches the first forward slash in requests
  • mod_rewrite excludes the first forward slash requests

Think of mod_rewrite as the Hulk and mod_alias as the Flash. It’s quicker to let Flash do it, but the Hulk is there just in case.