问题原文
原帖链接 · pg. · CC BY-SA 3.0
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?
已采纳解答
原帖链接 · MrWhite · CC BY-SA 3.0
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.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
