Apache RewriteRules - When do you NOT use the [L] flag?

I understand that the [L] flag should stop any subsequent RewriteRules, but I seem to add [L] as a question to each RewriteRule, and this is what is part of almost every rule found in code snippets and examples on the Internet.

I really don’t understand when you want and don’t want to use the [L] flag, because it seems that all the RewriteRules I've ever written worked with or without the [L] flag.

Can someone provide an example of a rule that requires [L] and one that should not have [L]?

+8
.htaccess mod-rewrite
source share
1 answer

On top of my head when you don't want to use L :

  • If you need to encode rewrite with N flag

     # Replace all instances of "aaa" with "zzz" RewriteRule ^(.*)aaa(.*)$ /$1zzz$2 [N] 
  • When you logically join a rewritable set together using the C flag

     # replace "old" with "new" but only if the first rule got applied RewriteRule ^special/(.*)$ /chained/$1 [C] RewriteRule ^(.*)/old/(.*)$ /$1/new/$2 [L] 
  • If you need to skip some rules using the S flag (taken from apache docs, since I can't come up with a working example)

     # Is the request for a non-existent file? RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # If so, skip these two RewriteRules RewriteRule .? - [S=2] RewriteRule (.*\.gif) images.php?$1 RewriteRule (.*\.html) docs.php?$1 
  • If you want to redirect, but you need other rules to handle URIs before redirecting using the R flag

     # If host is wrong, redirect RewriteCond %{HTTP_HOST} bad.host.com RewriteRule ^stuff/(.*)$ http://good.host.com/$1 [R=301] # but not until we apply a few more rules RewriteRule ^(.*)/bad_file.php$ /$1/good_file.php [L] 

On the other hand, sometimes the L flag does not need to be used, but it ensures that rewriting will stop when this rule is applied. It simply simplifies the rules because it prevents other rules from interfering with each other, therefore it is generally harmless to include the L flag at the end of all your rules, because 99% of the time, you really just want to stay there.

Note that L stops only the current rewrite iteration. The rewrite mechanism will loop until the URI that is included in the engine becomes the same as the URI (the query string is not part of the URI).

+11
source share

All Articles