Wednesday, April 8, 2009

Some interesting Apache Rewrite rules

Example 1
I have a directory having installers for different languages. User can download installer for any language. If user requests an installer for a language that is not supported, then the “en” installer has to be provided.

These installers are stored as -

<DOCUMENT_ROOT>/installers/<TWO_CHARS_LOCALE>/installer.exe like,
<DOCUMENT_ROOT>/installers/en/installer.exe,
<DOCUMENT_ROOT>/installers/de/installer.exe etc.

User can request an installer using the link http://www.mysite.com/installers/en/installer.exe

How do we achieve this language fallback – if an installer for a language is not available, provide English installer?

One way of achieving it is to write a 404 handler.

But how about writing a simple rewrite rule?

RewriteEngine On
RewriteLog "logs/rewrite.log"
RewriteLogLevel 9
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f [NC]
RewriteRule (^/installers)/../(installer.exe)$ $1/en/$2 [L]

More examples to follow soon ..

2 comments:

Sudheer Krishna said...

what is -f ? NC ?


can u explain how ur problem is solved in this case ?

Pranav Kumar Varshney said...

Here I check if the requested file does not exists which is !-f. NC is nocase which makes the test case-insensitive.

If file does not exists for the requested 2 chars locale which is represented as .., I replace it with 'en' and en installer is served.