I would like to ask a question in order to understand how Apache processes rewrite rules specified in the .htaccess file.
On my site I used a classical organization of the pages in categories, each category having more than one section:
http://www.mysite.com/category/section.html.
However, there are no html pages, everything is processed by the code in pages.php. Using a simple rewrite rule, URLs like the one above are mapped onto:
http://www.mysite.com/pages.php?cat=category&page=section
I decided to rename a section from section1 to section1-xxx. In order to serve requests for the old name (section1), I added a simple rule to map section1.html on section1-xxx.html.
The first rules I added in the .htaccess were the following:
R1
RewriteRule ^CAT1/section1.html$ CAT1/section1-xxx.html [NC]
where CAT1 is the name of a category.
R2
RewriteRule ^CAT1/(.*).html$ pages.php?cat=CAT1&page=$1 [L,NC]
My idea was to apply R1 and then R2. However, when those rules are applied, I end up with an unexplainable (for my brain) URL.
When the following page is requested
http://www.mysite.com/CAT1/section1.html
the URL is first transformed in
http://www.mysite.com/CAT1/section1-xxx.html/section1.html
then in
http://www.mysite.com/pages.php?cat=CAT1&page=section1-xxx.html/section1
Out of curiosity, I added the L (flag) to rule R1:
RewriteRule ^CAT1/section1.html$ CAT1/section1-xxx.html [L,NC]
and everything worked fine. Now http://www.mysite.com/CAT1/section1.html is served via:
http://www.mysite.com/pages.php?cat=CAT1&page=section1-xxx
Now the questions:
- Why did I get that URL before adding the L flag to rule R1?
- The L flag should indicate to apply the matching rule and then stop using other rules. However, with the L flag set, both R1 and R2 are applied. Why?
Thanks for your time.
Regards,
A.
The [L] flag can have unexpected results if we 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.
As you explained add L to R1.(R1 redirects something.html to someone.html ie you nedd html page their!)