Run
Run

Reputation: 57176

How to rewrite a url with a question mark?

Is it possible to rewrite an url with a question a mark in it?

For instance,

http://localhost/mysite/search?tag=mars

to become this,

index.php?url=search&tag[key_name]=mars

I tried with this, but no good at all,

RewriteRule ^search?tag=([a-zA-Z0-9\-]+)/?$  index.php?url=search&tag[key_name]=$1&type=tag [L,QSA]

Any suggestions?

EDIT:

For %1,

RewriteCond %{QUERY_STRING} (?:^|&)tag=([^&]+)
RewriteRule ^search$ index.php?url=search&tag\%5Bkey_name\%5D=%1&type=tag [L]

Result,

print_r($_GET);

Array
(
    [url] => search
    [tag] => Array
        (
            [key_name] => 
        )

    [type] => tag
)

For %0,

RewriteCond %{QUERY_STRING} (?:^|&)tag=([^&]+)
RewriteRule ^search$ index.php?url=search&tag\%5Bkey_name\%5D=%0&type=tag [L]

Result,

print_r($_GET);

Array
(
    [url] => search
    [tag] => Array
        (
            [key_name] => tag=mars
        )

    [type] => tag
)

Upvotes: 1

Views: 234

Answers (1)

Salman Arshad
Salman Arshad

Reputation: 272106

Query strings cannot be matched inside RewriteRule. You must use RwwriteCond instead:

RewriteCond %{QUERY_STRING} (?:^|&)tag=([^&]+)
RewriteRule ^search$ index.php?url=search&tag\%5Bkey_name\%5D=%1&type=tag [L]

Here:

  • [ and ] are urlencoded as %5b and %5D
  • \% is used to escape the literal % characters
  • %0 ... %9 are the strings that were matched/captured in RewriteCond clause. This is just the way you use $0 ... $9 for RewriteRule
  • QSA flag is not required
  • (^|&) matches beginning of input (e.g. in tag=mars&foo=bar) or & (e.g. in foo=bar&tag=mars)
  • ?: makes mod_rewrite not capture this group (other this match would go in %1, next one in %2, etc)

Your PHP script will get:

$_GET["url"]  : search
$_GET["tag"]  : Array([key_name] => mars)
$_GET["type"] : tag

Upvotes: 2

Related Questions