大网数据广告活动
网站运营与故障问答

How to pass a match from the regex in a condition to the rule in .htaccess

· 52CE 我爱测

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} RewriteCo…

问题原文

原帖链接 · 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2018-01-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。