How do I create a rewrite rule that only matches a request with no query string?

http://www.mysite.com/index.php

should remap to:

http://www.mysite.com/

BUT

 http://www.mysite.com/index.php?page=some_page

Should be left alone.

I'm trying this:

RewriteRule ^/index.php$   http://www.mysite.com/ [R=301,L]

...But it's matching anything that starts with /index.php even though I've explicitly ended the pattern with a dollar sign.

UPDATE:

The only rules before this one are:

 RewriteCond %{HTTP_HOST}   ^mysite.com [NC]
 RewriteRule ^/(.*)         http://www.mysite.com/$1 [R=301,L]

The intention is to redirect non www links to the www version.

link|improve this question

72% accept rate
This should work as expected, the syntax is fine. Are you including this as the first rule in your chain of rewrites? Is there a conflicting rewrite elsewhere (in httpd.conf vs .htaccess, etc?) Perhaps something is short-circuiting the rules somewhere and this is never reached. Just some thoughts. – Sam Halicke Nov 13 '09 at 0:10
I've updated the original question to include the two rules before this one. – Nick Nov 13 '09 at 0:22
feedback

4 Answers

The [L] flag on the first set of rules here:

RewriteCond %{HTTP_HOST}   ^mysite.com [NC]
RewriteRule ^/(.*)         http://www.mysite.com/$1 [R=301,L]

L means Last -- Apache will stop processing rules for this iteration when it is reached.

Remove the L flag and you should be fine.

link|improve this answer
feedback

RewriteCond ! %{QUERY_STRING} would match requests without a query string.

You can also add the following to turn on logging and debugging of mod_rewrite RewriteLog logs/rewrite_log RewriteLogLevel 3

Be aware that this can slow you site down and fill up your logs so only use it for debugging.

link|improve this answer
It didn't work- the condition didn't seem to match anything, so the rule never ran. This worked though: RewriteCond %{QUERY_STRING} ^$ – Nick Nov 13 '09 at 10:24
feedback

All these rewrites are RegExps which are quite slow. It should be a bit faster if you do it from index.php:

if (!strlen($_SERVER["QUERY_STRING"])) header("Location: /");
link|improve this answer
feedback
up vote 0 down vote accepted

Here's the solution I came up with:

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/index.php$   / [R=301,L]
link|improve this answer
Please mark this as the correct answer then. – pauska Nov 13 '09 at 11:11
1  
I tried- It wont let me. It says I have to wait 2 days. – Nick Nov 14 '09 at 0:00
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.