Home : Internet : Server : Apache : Mod Rewrite : Using the [L] Last flag

Using [L]

The [L] flag can have unexpected results if you are not clear on how the module behaves. Note that the following only applies when mod_rewrite is used in a .htaccess file. The [L] flag behaves exactly as expected when used in httpd.conf.

The L flag will tell Apache to stop processing the rewrite rules for that request. Now what is often unrealised is that it now makes a new request for the new, rewritten filename and begin processing the rewrite rules again.

Therefore, if you were to do a rewrite where the destination is still a match to the pattern, it will not behave as desired. In these cases, you should use a RewriteCond to exlude a certain file from the rule.

Example 1 - Rewrite everything to single script

Assume you are using a CMS system that rewrites requests for everything to a single index.php script.

RewriteRule ^(.*)$ index.php?PAGE=$1 [L,QSA]

Yet every time you run that, regardless of which file you request, the PAGE variable always contains "index.php".

Why? You will end up doing two rewrites. Firstly, you request test.php. This gets rewritten to index.php?PAGE=test.php. A second request is now made for index.php?PAGE=test.php. This still matches your rewrite pattern, and in turn gets rewritten to index.php?PAGE=index.php.

One solution would be to add a RewriteCond that checks if the file is already "index.php". A better solution that also allows you to keep images and CSS files in the same directory is to use a RewriteCond that checks if the file exists, using -f.

Example 2 - Rewrite by exclusion

This is a more complex situation - you want to rewrite certain requests with your first RewriteRule, then rewrite the rest somewhere else.

RewriteRule ^articles/([0-9]+)-(.*)\.html$ article.php?id=$1 [L]
RewriteRule .* index.php

Here, articles/ gets rewritten to article.php, which gets rewritten to index.php. Again, we will need some conditionals so you would want to add in a RewriteCond as described in article 1.