You need to either:
- Check that the destination file (with the
.php
extension) exists before internally rewriting to it
- Avoid rewriting directories (for which the document root is one).
- Avoid rewriting the document root only (as in your example).
For example, to avoid rewriting the document root only, as in your specific example, you can modify the existing RewriteCond
directive:
# Add .php extension for final internal redirect
RewriteCond %{REQUEST_URI} ^(.*)$
to read:
RewriteCond %{REQUEST_URI} ^(/.+)$
/.+
matches a slash followed by something, which would exclude the document root, since the document root is naturally a slash by itself.
To avoid rewriting all directories (of which the document root is one), you can add an additional condition to avoid rewriting URLs that map to a physical directory. For example:
RewriteCond %{REQUEST_URI} ^(/.+)$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.php$ %1.php [NC,L]
However, if you have directories that are accessible then you should modify your existing rule that removes trailing slashes, otherwise, you will likely get a redirect loop when requesting a directory (since mod_dir will append a slash by default). For example:
# Remove trailing slashes
RewriteRule ^(.*)\/$ $1 [NC,L,R=301]
Should be modified to include the same condition as above:
# Remove trailing slashes, unless the request maps to a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [L,R=301]
Also, no need for the NC
flag here. And there is no need to escape the slash in the RewriteRule
pattern.
I assume you must also have a RewriteBase
directive defined elsewhere in you file, otherwise, this will likely result in an invalid redirect in .htaccess
.