2

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
  • 42,784
  • 4
  • 49
  • 90
IXN
  • 322
  • 1
  • 2
  • 8

1 Answers1

5

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.

MrWhite
  • 42,784
  • 4
  • 49
  • 90