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

Simple .htaccess language question (redirection)

· 52CE 我爱测

I do not know the language of .htaccess, thus the newbie question. I have this code: RewriteEngine On RewriteCond %{QUERY_STRING} ^m=1$ RewriteRule (.*) /$1? [R=301,L] It redirects any urls that have this extension ?m=1 to the ur…

问题原文

原帖链接 · IXN · CC BY-SA 3.0

I do not know the language of .htaccess, thus the newbie question. I have this code:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^m=1$
RewriteRule (.*) /$1? [R=301,L]

It redirects any urls that have this extension ?m=1 to the url without the extension.

I would like to redirect also ?m=0 (or ?m=anything ) to the original url. How should I re-write the above code? Would that just be RewriteCond %{QUERY_STRING} ^m=*$

已采纳解答

原帖链接 · MrWhite · CC BY-SA 3.0

This is as much a question about regular expressions (regex) than .htaccess. The second argument (CondPattern) to the RewriteCond directive takes a regex, not a wildcard expression. (Specifically, Apache uses the PCRE flavour of regex.)

Would that just be RewriteCond %{QUERY_STRING} ^m=*$

No. This assumes the argument is a simpler wildcard type expression (where * simply matches 0 or more characters) - it is not. In regex-speak, the * matches 0 or more occurrences of the preceding character/group. So, this would match exactly ?m (0 occurrences), ?m= (1 occurance), ?m== or ?m===, etc. Not your intention at all. It wouldn't even match your original URL.

Assuming the m URL parameter always occurs at the start of the query string, then to match ?m=<anything>, you could simply use the regex ^m=. This matches any query string that starts m= followed by anything (including nothing). For example:

RewriteCond %{QUERY_STRING} ^m=

However, you generally want regex to be as restrictive as possible (although that may not apply in this case). For example, to match any URL that contains the query string ?m=N only, where N is a digit 0-9 and there are no other URL parameters, then you could do something like:

RewriteCond %{QUERY_STRING} ^m=\d$

Where \d is a shorthand character class for any digit (the same as [0-9]).

Aside: Test with 302 (temporary) redirects to avoid caching problems and clear your browser cache before testing.

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

资料来源与适用范围

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

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

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