Htaccess rewrite causes 500 error instead of 404

I recently added this little code to my file .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]

Well, I understand what is happening here, I think. This little code to remove PHP file extensions causes a loop if the document is not found. This loop causes a server 500 error instead of the (correct) 404. Unfortunately, I understand very little what these rewrites actually do, so I don’t know how to rewrite it to initiate this redirection only if the document exists.

I did some reading, and I'm not sure what Apache considers a “regular” file. I mean this works, but why would the first line not be -finstead !-f? Is the -uonly way to achieve this?

+3
source share
3 answers

You should check if the new path points to an existing file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L,QSA]

Otherwise, you will get infinite recursion (error 500).

+19
source

The intent of these rules, as you said, allows someone to request a page without including the PHP extension. Therefore, if you have a file on example.com called about.php , then someone can use the URL http://example.com/about to access it.

, - http://example.com/about.php, , http://example.com/about.php.php. , CSS .. , 2 RewriteConds, , , (!-f) (!-d), .

, 500, , Apache , htaccess . error_log, , - .

+2

-, , mod_rewrite:

mod_rewrite

mod_rewrite cheat sheet

The problem you see is that it checks both conditions, the default value is [AND], when you only want to check it, try the following:

RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]
0
source

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


All Articles