php.htaccessapache2.4

.htaccess 404 error not working while accessing file without extension


example.com/home.php <-- file available and Working without .php extension

example.com/home <-- Working

example.com/home1.php <-- File not exist showing 404 error mentioned in htaccess example.com/home1 <-- The file does not exist, and it shows "File not found" . htaccess rule not working here

.htaccess file

RewriteEngine On 
DirectoryIndex home.php 
Options -Indexes 
Options -MultiViews
Options +FollowSymLinks


RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# RewriteRule ^([^\.]+)$ $1.html [PT,L]
RewriteRule ^([^\.]+)$ $1.php [PT,L]

ErrorDocument 404 http://example.com/404.php
ErrorDocument 403 http://example.com/403.php

Solution

  • This is probably caused by the way PHP is installed/routed on your system. If you check the HTTP response headers of the "File not found" response, I guess you will see this is from a different/proxy server (perhaps Nginx)?

    However, you shouldn't be blindly rewriting requests to .php when the original request simply does not exist. (/home1 is first being internally rewritten to /home1.php, which is then triggering a 404, not /home1 - the original request.) You should instead be checking that <requested-url>.php exists before rewriting the request.

    For example, try the following instead:

    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^.]+)$ $1.php [L]
    

    Additional notes...

    ErrorDocument 404 http://example.com/404.php
    ErrorDocument 403 http://example.com/403.php
    

    By specifying an absolute URL in the ErrorDocument directive this will result in a 302 (temporary) redirect to the error document and the original HTTP error status will be lost. (ie. the client sees a 302, not a 404 - bad for users and SEO.)

    (And HTTP, not HTTPS?)

    This should generally be written using root-relative URL-paths in order to trigger an internal subrequest for the error document (thus preserving information from the original request), not an external redirect. For example:

    ErrorDocument 404 /404.php
    ErrorDocument 403 /403.php