mod_rewrite Revisited

By Deane Barker on October 8, 2004

A few weeks ago, I posted about how to use some Apache directives to protect your content editors from themselves. In that post, I said:

…there is a way to configure mod_rewrite to check two roots for a file. If it doesn’t find a file in the actual Web root, it will check the alternate Web root (the editor’s directory). Thus, you, as the developer, have “first rights” to any URL (“/search.php” for instance).

Some people wrote and asked about this. Here are the directives:

RewriteCond [path to Web root]/%{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /~editor$1 [L]

What this does is take any request, like:


And, if it doesn’t find a matching file in the Web root, rewrites it to:


(Note that this rewrite is invisible to the visitor. It’s not a redirect, whereby their browser is told about it and the URL in the address bar changes. The rewrite is on the server. They’ll never know the difference.)

So, you, as the developer, get “first dibs” on URLs. If you don’t have one in the Web root (to which the editor doesn’t have access), then Apache will try the editors folder.

The way it works is that when mod_rewrite hits our RewriteRule directive (and — based on the pattern — knows it’s going to execute it), it backtracks and makes sure all the preceding RewriteCond directives are true. So it hits our rule, jumps back one step and evaluates the RewriteCond.

The RewriteCond says, “Is there a file at this file path?” (The “-f” flag means to check if it’s a file, and the “!” modifier means “not.”) If the answer is true, then it executes the RewriteRule and rewrites the URL. If there’s nothing there either, you’ll get a 404. (The “[L]” flag means “Last Rule,” so you don’t get an infinite loop.)

Using the same theory, here’s some code to “catch” any request to an image that does not exist in a certain directory and replace it with a “No Image” image:

RewriteCond [path to Web root]/%{REQUEST_FILENAME} !-f
RewriteRule ^/People/Images/.*$ /People/Images/NoImage.jpg [L]

This will ensure that you get a nice, tidy “No Image” image for any 404 to the “People/Images” directory.



  1. Here’s a question you might be able to help with. Know of any mod_rewrite equivalents for IIS? Documents, links, what-have-you.

    I’m personally using Apache … but at work … you know the drill.

  2. No reason you couldn’t use mod_rewrite and apache to front a servlet engine. If you’re using tomcat, it has an apache plugin that would probably allow this.

Comments are closed. If you have something you really want to say, email and we‘ll get it added for you.