htaccess: secret proxy


I always keep fighting over setting up htaccess rules. Writing these rules is like playing with a black box; if you're doing it right, you don't know how right you are. If you're doing it wrong, all you get is a 500. Very annoying.

I wanted to use for link gatherer and for url shortner. For the shortner I set up a simple script. However, for that I needed some rewrite magic to service a "catch-all". Of course, this wasn't as easy as it should be. Even though the end-result turned out as easy as I wanted it to be. *sigh*

Anyways. There's a pro tip here. It seems htaccess has an interesting function for this; RewriteLog and RewriteLogLevel. Read here for more information (and an example). See also my previous note.

For my htaccess I needed to be able to check whether the file existed. If it didn't, it should check a secret directory for a file with that name. If that exists, go knock yourself out. That seemed difficult, but I eventually managed.

Code: (htaccess)
RewriteEngine on

RewriteRule ^index.php$ http://%{HTTP_HOST}/ [L,R=301]

RewriteCond %{DOCUMENT_ROOT}/dir1/dir2/%{REQUEST_URI}.php -f
RewriteRule ^(.+) %{DOCUMENT_ROOT}/dir1/dir2/%{REQUEST_URI} [L]

The first rule rewrites to
The second rule is a condition. The requested file must not exist.
The third rule is also a condition. The requested file should exist in the target directory.
The fourth rule says, redirect there internally. But only when the previous conditions apply.


The next hackathon I'm going to commit to writing a htaccess simulator. It should accept a directory structure, configurable with a set of htaccess rules for each directory and a URL. It should then show the rewrites or redirects being executed. Probably much like RewriteLog would do. Except that I can't check that because I don't have enough rights on my server (or it causes a 500 either way) and I don't want to set up a server locally for it.

Edit: Maybe I won't need to anymore!

Ohwell, don't think I'll be attending a hackathon any time soon :p

Hope it helps!