user1066994
user1066994

Reputation:

Apache mod_rewrite issue

I am trying to send every request to www.example.com/user/ to www.example.com/user.php?id=0 using this

RewriteRule ^user/$ user.php?id=0

Basically, if someone is accessing www.example.com/user/ with no user id, the site will default to id = 0.

However, when I type www.example.com/user/ Apache seems to simply serve the user.php file, completely ignoring the RewriteRule. Any idea on why this is happening?

Thank you.

I should mention that this only happens if I use the same word in the URL as the php file's name. For example, if I were to use

RewriteRule ^yes/$ user.php?id=0

Going to www.example.com/yes/ would apply the RewriteRule just fine. So it seems that Apache looks for a file with that name and ignores the RewriteRule. And no, adding a [L] flag did not help.

Here's my .htaccess:

RewriteEngine On
RewriteRule ^user/$ user.php?id=0
RewriteRule ^user/([0-9]+)$ user.php?id=$1 

Upvotes: 4

Views: 282

Answers (2)

Book Of Zeus
Book Of Zeus

Reputation: 49895

try this:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^user/$ user.php?id=0 [L,NC,QSA]
RewriteRule ^user/([0-9]+)/?$ user.php?id=$1 [L,NC,QSA]

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

from: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_l

Upvotes: 6

Clive
Clive

Reputation: 36965

I think your rewrite rules are in the wrong order, and you're not using the [L] flag to tell apache not to run any more rules when a rule's been matched. Also you could use the + operator instead of * to match at least one digit in your second rule:

RewriteRule ^user/$ user.php?id=0 [L]
RewriteRule ^user/([0-9]+)$ user.php?id=$1 [L]

Upvotes: 0

Related Questions