Rod Michael Coronel
Rod Michael Coronel

Reputation: 592

Handling '?' in mod_rewrite

I have a page that asks a user to confirm if he wants to continue or cancel and I use a rewrite rule for it:

RewriteRule ^click/(.+)$ aclick.php?url=$1 [B]

The problem arises when the URL has a question mark. For example:

http://example.com/click/yahoo.com/mobile/?s=ladygaga

My goal is that this URL be re-written as:

http://example.com/aclick.php?url=yahoo.com/mobile/%3fs=ladygaga

So that the continue button will proceed to: 'http://yahoo.com/mobile/?s=ladygaga'

However, the continue button is just linked to 'http://yahoo.com/mobile/'.

Does anyone have an idea to fix this?

Upvotes: 2

Views: 73

Answers (1)

yasu
yasu

Reputation: 1364

Use %{QUERY_STRING} as follows. You have to refer REDIRECT_QUERY_STRING instead of QUERY_STRING.

RewriteRule ^click/(.+) aclick.php?url=$1?%{QUERY_STRING} [B,L]

B flag will escape the string excessively. If you access http://example.com/click/yahoo.com/mobile/?s=ladygaga, the query string will be url=yahoo%2ecom%2fmobile%2f?s=ladygaga. (It does not cause bad influence.)

In case that URL have no query string, redundant "?" is added to the end of query string. To prevent this, use RewriteCond:

# If URL have any query string, then
RewriteCond %{QUERY_STRING} .
RewriteRule ^click/(.+) aclick.php?url=$1?%{QUERY_STRING} [B,L]
# otherwise,
RewriteRule ^click/(.+) aclick.php?url=$1

You can simply written as follows:

RewriteRule ^click/(.+) aclick.php

Program aclick.php can refer environment variables REQUEST_URI, REDIRECT_URL, QUERY_STRING etc.

Upvotes: 2

Related Questions