Question

I want to remove extension from request and add it on the server side, so I wrote this code in the .htaccess file:

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

This code work great in standard use. For example if I have file in HOME/foo/bar.php
and I request it like localhost/foo/bar, the code is working and redirect me to the correct file.

But if my request is localhost/foo/bar/ (backslash at the end), or localhost/foo/bar/a I got internal server error (500), and in the log file I got Request exceeded the limit of 10 internal redirects.

I have been tested the code and saw that the %{REQUEST_FILENAME} ignores the wrong suffix of the request /a so it see only HOME/foo/bar, but the RewriteRule $1 dose not ignore it.

Whats wrong with my code?

Was it helpful?

Solution

Try this rule instead:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

This takes care of trailing slash issue as well as making sure correct php file exists before rewriting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top