1

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=$1&question=%{REQUEST_URI}

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

  • 1
    Why are not testing apples|bananas in URI at the RewriteRule stage? – Patrick Mevzek Jan 26 '18 at 21:49
1
RewriteCond %{REQUEST_URI} /(apples|bananas)/*
RewriteRule . /page/faqs.php?cat=$1&question=%{REQUEST_URI}

Almost. But you need to use %1 instead of $1 as a backreference to the first captured group in the last matched CondPattern (RewriteCond pattern). $1 is a backreference to the first captured group in the RewriteRule pattern (but you have none, so $1 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 $1 like you are doing. For example:

RewriteRule ^(apples|bananas)/ /page/faqs.php?cat=$1&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.

  • 1
    Thank you so much! You've made my life much easier today! – pg. Jan 26 '18 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.