Search code examples
apache.htaccessmod-rewrite

Using multiple rewrite rules?


I have a simple .htaccess file with the contents below.

<IfModule mod_rewrite.c>
     RewriteEngine on

     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d

     RewriteRule ^(.*)$ index.php?s=$1 [L]
</IfModule>

I want to add this rule.

RewriteRule ^p$ index.php?p= 

I tried doing this below but it doesn't work. It seems like both rules are being run. I have tried a couple of different flags and again have had no luck. Could someone tell me how to get this working please.

<IfModule mod_rewrite.c>
     RewriteEngine on

     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d

     RewriteRule ^p$ index.php?p= 
     RewriteRule ^(.*)$ index.php?s=$1 [L]
</IfModule>

Solution

  • You should know first that the rewrite conditions only affect the following rewrite rule, an you added your new rule between the rewrite conditions and the rewrite rule, that means they will now affect your new rule only and not the old one (what you have in you code is that the rewrite rules are only executed if the targeted url is not a file or a directory), so if you want your old rule to be still affected by the rewrite condition, you will have to add your new rule before the rewrite conditions.

    For your issue, I think zessx has answered enough (It is fixed by adding the [L] flag).

    In the end you should have something like this :

    <IfModule mod_rewrite.c>
         RewriteEngine on
    
         RewriteRule ^p$ index.php?p= [L]
    
         RewriteCond %{REQUEST_FILENAME} !-f
         RewriteCond %{REQUEST_FILENAME} !-d
         RewriteRule ^(.*)$ index.php?s=$1 [L]
    </IfModule>