Php – Trouble with htaccess multiple rewrite rules

.htaccessapache-2.4mod-rewritePHPredirection

I have a below criteria

If a query string matches Microwave_Ovens text I need to replace with Microwave-Ovens (replace underscore by hyphen) in Request URI.

It is working as expected for the first set of 3 lines mentioned below. I actually need to do the same for some other type (assume Vacuum_Cleaners) also the same. I added second set of 3 lines but it is not working. Whatever I specify first is working only.

My rewrite conditions & rules are as follows:

RewriteCond %{QUERY_STRING} ^(.*)Microwave_Ovens(.*)$
RewriteRule ^([^_]*)_+([^_]*)$ /Mr10q/$1-$2?%1Microwave-Ovens%2 [R=301,L]
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]

RewriteCond %{QUERY_STRING} ^(.*)Vacuum_Cleaners(.*)$
RewriteRule ^([^_]*)_+([^_]*)$ /Mr10q/$1-$2?%1Vacuum-Cleaners%2 [R=301,L]
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]

Can anyone please suggest me what I am doing wrong here

Best Answer

RewriteCond %{QUERY_STRING} ^(.*)Microwave_Ovens(.*)$
RewriteRule ^([^_]*)_+([^_]*)$ /Mr10q/$1-$2?%1Microwave-Ovens%2 [R=301,L]
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]

Your rules appear to do a lot more than you've stated in the question? But the main problem here would seem to be the second RewriteRule directive. The preceding RewriteCond directive(s) only apply to the first RewriteRule directive. So, the second RewriteRule will run unconditionally and catch any request that might contain Vacuum_Cleaners.

Since you have duplicated this directive in the second rule block, then maybe simply removing the first one will be sufficent. For example:

# 1
RewriteCond %{QUERY_STRING} ^(.*)Microwave_Ovens(.*)$
RewriteRule ^([^_]*)_+([^_]*)$ /Mr10q/$1-$2?%1Microwave-Ovens%2 [R=301,L]

# 2
RewriteCond %{QUERY_STRING} ^(.*)Vacuum_Cleaners(.*)$
RewriteRule ^([^_]*)_+([^_]*)$ /Mr10q/$1-$2?%1Vacuum-Cleaners%2 [R=301,L]

# 3
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]