Kamrul Khan
Kamrul Khan

Reputation: 3360

How to match question mark in .htaccess

I have the following regex in my .htaccess

RewriteRule ^([a-z]+)/([a-z]+)/\?(.+)$ ./default.php?controller=$1&action=$2&$3

Im expecting, if I supply an URL like mysite.com/controller/action/?v=2 it will be translated into mysite.com/default.php?controller=controller&action=action&v=1

However, it doesnt work. I tried doing

RewriteRule ^([a-z]+)/([a-z]+)/[?](.+)$ ./default.php?controller=$1&action=$2&$3

and

RewriteRule ^([a-z]+)/([a-z]+)/[\?](.+)$ ./default.php?controller=$1&action=$2&$3

None worked. Then I tried replacing the ? (question mark) by x

RewriteRule ^([a-z]+)/([a-z]+)/x(.+)$ ./default.php?controller=$1&action=$2&$3

and tried passing an URL like mysite.com/controller/action/xv=2

That worked just as expected. I tried testing my regex and it seems alright. What wrong am I doing ?

Upvotes: 2

Views: 321

Answers (2)

Mike Rockétt
Mike Rockétt

Reputation: 9007

Query strings are not detected in the rules themselves. For reference, these need to be checked with a separate condition that checks the value of QUERY_STRING.

However, you actually do not need to do this in your case, as you only need to use the QSA (Query String Append) flag to append v=1 query parameter to the new URI.

RewriteRule ^([^/]+)/([^/]+)/$ default.php?controller=$1&action=$2 [QSA,L]

Now, when requesting /mycontroller/myaction/?v=1, Apache will serve default.php?controller=mycontroller&action=myaction&v=1.

If you would like to make the last trailing slash optional, then add a question mark after it (^([^/]+)/([^/]+)/?$).

For reference, [^/]+ means "one or more characters that is not a forward slash".

Upvotes: 3

Shaun Cockerill
Shaun Cockerill

Reputation: 926

Query strings aren't interpreted in the RewriteRule directly, however, you can easily append it onto the end.

Try this:

RewriteRule ^([a-z]+)/([a-z]+)/$ ./default.php?controller=$1&action=$2&%{QUERY_STRING}

Upvotes: 2

Related Questions