Problem with Apache mod_rewrite

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

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

Basically, if someone accesses www.example.com/user/ without a user ID, the site will default to id = 0 .

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

Thanks.

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

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

Going to www.example.com/yes/ apply the RewriteRule just fine. Therefore, it seems that Apache is looking for a file with that name and ignores the RewriteRule. And no, adding the [L] flag didn't help.

Here is my .htaccess:

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

try the following:

 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, further rules will not 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

+6
source

I think your rewrite rules are in the wrong order and you are not using the [L] flag to tell apache not to run more rules when the rule has been matched. You can also use the + operator instead of * to match at least one digit in the second rule:

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

Source: https://habr.com/ru/post/1383196/


All Articles