Mobile app version of vmapp.org
Login or Join
Shelton105

: How to pass a match from the regex in a condition to the rule in .htaccess I have an .htaccess file with rules like this: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d

@Shelton105

Posted in: #Htaccess #RegularExpression

I have an .htaccess file with rules like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /apples/*
RewriteRule . /page/faqs.php?cat=apples&question=%{REQUEST_URI}

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /bananas/*
RewriteRule . /page/faqs.php?cat=bananas&question=%{REQUEST_URI}


I want it to work like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(apples|bananas)/*
RewriteRule . /page/faqs.php?cat=&question=%{REQUEST_URI}


with the being the matched value (apples or bananas). How can I pass something like this from a condition to a rule?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Shelton105

1 Comments

Sorted by latest first Latest Oldest Best

 

@Ann8826881

RewriteCond %{REQUEST_URI} /(apples|bananas)/*
RewriteRule . /page/faqs.php?cat=&question=%{REQUEST_URI}



Almost. But you need to use %1 instead of as a backreference to the first captured group in the last matched CondPattern (RewriteCond pattern). is a backreference to the first captured group in the RewriteRule pattern (but you have none, so would always be empty in this example).

However, as @PatrickMevzek suggested in comments, you should be performing this check on the URL in the RewriteRule pattern instead (more efficient and one less directive). In this case you would use like you are doing. For example:

RewriteRule ^(apples|bananas)/ /page/faqs.php?cat=&question=%{REQUEST_URI} [L]


You didn't have an anchor in your original CondPattern (/(apples|bananas)/*) so this would have matched anywhere inside the URL. I've assumed this should be at the start of the URL-path? Also the trailing * is not doing what you think it is. The * in regex speak repeats the previous character 0 or more times (it's not a "wildcard" character). So, this would have only served to match multiple slashes (which I doubt was the intention)!

I've also added the L (last) flag. I assume you don't want any other rewrites to occur after this one? This doesn't really matter if this is the only mod_rewrite directive in the file, but if you added later directives then the L may be required.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme