Kirill Smirnov
Kirill Smirnov

Reputation: 1532

Strange behavior in apache mod_rewrite

I have a problem with understanding mod_rewrite behavior. I'll illustrate this with an example. I have 3 files in my root directory: .htaccess, index.php and test.php. The content of files:

.htaccess

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) ?link=$1 [L]

index.php

<?php
$db = mysqli_connect('localhost', 'root', '', 'mydb'); 
$db->real_query ("INSERT INTO `test` (`str`) VALUES ('test_string')");
print_r($_GET);
?>

test.php

<?php
$db = mysqli_connect('localhost', 'root', '', 'mydb'); 
$db->real_query ("INSERT INTO `test` (`str`) VALUES ('another_test_string')");
print_r($_GET);
?>

So when I go to my site's root folder with the browser, two strings are inserted in database - 'test_string' and 'test_string'. If I go to /test.php, also two strings will be inserted - one from index.php script - 'test_string' and one from test.php string - 'another_test_string'. If I remove rewrite rules from .htacess, only one string will be inserted for both pages. I cannot understand such behavior - why all scripts are executed twice? And especially I don't understand why this happens with test.php since I wrote RewriteCond %{REQUEST_FILENAME} !-f, so no rewrites should be done.
Thank you in advance.

Upvotes: 4

Views: 184

Answers (1)

hakre
hakre

Reputation: 197564

The php code you have will insert into the database once that fragment of code is processed.

If you execute it more than once, you will see more inserts in the database.

However rewrite rules are executed once only, too.

So what you experience is likely totally unrelated with your rewrite rules. If you do not trust me, enable logging for the rewrites (see apace docs) and follow the trail.

You probably have sit too long in front of the computer, so just get a cup of tea, relax and find that bug.

Upvotes: 2

Related Questions