Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I understand that the [L] flag is supposed to stop any further RewriteRules being processed but I seem to add [L] as a matter of course to every RewriteRule, and this is something that is part of nearly every rule found in code snippets and examples online.

I don't really understand when you would and wouldn't want to use an [L] flag because it seems like all the RewriteRules I ever write work with or without the [L] flag.

Can somebody provide an example of a rule that needs [L] and one that shouldn't have [L]?

like image 832
BadHorsie Avatar asked Aug 02 '12 11:08

BadHorsie


1 Answers

Off the top of my head, times when you don't want to use L:

  • When you need to loop a rewrite with the N flag

    # Replace all instances of "aaa" with "zzz"
    RewriteRule ^(.*)aaa(.*)$ /$1zzz$2 [N]
    
  • When you logically chain a set of rewrites 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]
    
  • When you need to skip some rules using the S flag (taken from apache docs, since I can't think of 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
    
  • When you want to redirect but need to have other rules process the URI before the redirection 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 doesn't need to be used, but it ensures that rewriting stops when that rule gets applied. It just makes coming up with rules easier because it keeps different sets of rules from interfering with each other, so it's usually an on-the-safe-side thing to just harmlessly include an L flag at the end of all your rules because 99% of the time, you really just want to stop there.

Note that the L only stops the current iteration of rewriting. The rewrite engine will loop until the URI that goes into the engine is exactly the same as the URI coming out (query string not part of URI).

like image 200
Jon Lin Avatar answered Dec 26 '22 17:12

Jon Lin