Prisoner
Prisoner

Reputation: 27618

Mod rewrite ? being included

This is my rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule ^index\.php?(.*)$ http://www.domain.com/$1 [R=301,L]

My input url is http://domain.com/test but the browser is redirected to http://www.domain.com/?/test when I expect http://www.domain.com/test. Tested here.

The idea is to redirect to www. but the problem is I'm using a custom framework which re-writes to index.php?$1.

Upvotes: 0

Views: 61

Answers (1)

larsks
larsks

Reputation: 311750

Please see UPDATE, below.

Your problem may be that ? is a regular expression metacharacter (like . and *):

? means zero or one of the previous expression. "pin?e" will match both "pine" and "pie". source

Try escaping it like this:

RewriteRule ^index\.php\?(.*)$ http://www.domain.com/$1 [R=301,L]

Your existing rule is looking for index.ph, possibly followed by p, and then collecting all remaining characters into $1 (which will include the ?).

UPDATE

Upon review, I've made some pretty elementary mistakes here. Allow me to correct them:

mod_rewrite only looks at the path portion of the URL...which means everything up to, but not including, the ? separating the query string from the path. So the rule I've listed above will never work, because the ? and following text isn't seen by RewriteRule.

You can match against the query string with a RewriteCond directive, which gives us:

RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^/index.php http://www.domain.com/%1 [R=301,L]

This dumps anything in the query string into %1, and then appends it to http://www.domain.com/...which almost works, but you'll find that a request like this:

http://domain.com/index.php?some/path

Becomes:

http://www.domain.com/some/path?some/path

We need to include the ? in our rewritten path to tell mod_rewrite to erase the query string, which gives us:

RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^/index.php http://www.domain.com/%1? [R=301,L]

Using this configuration on my system, a request for:

http://localhost/index.php?some/path

Returns:

HTTP/1.1 301 Moved Permanently
Date: Sat, 31 Mar 2012 00:39:34 GMT
Server: Apache/2.4.1 (Unix) OpenSSL/1.0.0g-fips mod_macro/1.2.1
Location: http://www.domain.com/some/path

Upvotes: 0

Related Questions