Last Updated on June 3, 2021 by Amit
Are you struggling to fix your RewriteRules with two identical patterns?
In this article I will show you how to fix it when you have two RewriteRules with same patterns in an htaccess file.
I know it’s a bit complicated for people who are new to htaccess to understand why their Rule failed but this article will explain the reason and provide you a working solution.
Rewrite engine reads rules from top to bottom
In an htaccess or server.config files , rules are read from top to bottom . Not just RewriteRule but all directives are read in this order. In your htaccess file the first line is read first.
Suppose, your htaccess file has the following two rules :
RewriteRule ^foo /index.php [L] RewriteRule ^foot /index.php [L]
As you can see we have two rules of the same pattern, the first rule has a catch-all pattern and it also matches the URL path foot .
The second rule is there created to match a request that starts with foot but for your surprise, the server will only read the first rule wether you type
foo or foot.
The reason behind this is that the both rules have identical patterns.
Fix RewriteRules with identical patterns
You can fix the above rules easily by swapping it. Change the order of the rules ,
RewriteRule ^foot /index.php [L] RewriteRule ^foo /index.php [L]
Now if you visit foo the engine will read the correct second rule
because the first one doesn’t match it.
Change the form of your URIs
If you have two RewriteRules of the same pattern then the most common issue you will face is Your first rule will be matched while the second one will have no effect.
The following is an example of RewriteRules with identical patterns :
RewriteEngine on RewriteRule (.*) /index.php [L] RewriteRule (.*) /index2.php [L]
Only the first rule above will be read by server. To fix this you need to change the form of your URIs. Change the regex of the first pattern to ^first/(.*)$ so that any URIs starting with /first can point to the correct index.php file and other URIs to index2.php.
first is just an example here , you change the pattern to whatever URI you want to set .