htaccess ErrorDocument not working with when removing php extension

.htaccess

# Security Headers
<IfModule mod_headers.c>
    Header set X-XSS-Protection "1; mode=block"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-Content-Type-Options "nosniff"
    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
    # Header set Content-Security-Policy ...
    Header set Referrer-Policy "same-origin"
    Header set Feature-Policy "geolocation 'self'; vibrate 'none'"
</IfModule>

# Index.php default 
RewriteEngine On
DirectoryIndex index.php

# Remove .php extension
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Error document handling
ErrorDocument 404 https://landon.pw/404
ErrorDocument 403 https://landon.pw/404

Options -Indexes

If I try landon.pw/a/, it will redirect to the 404. If I try landon.pw/a, it won't.

I believe the issue is because the way I am removing the php extension. When they go to /a, it is trying to serve a.php, which I guess is why it won't redirect files to the 404. I just don't know how to circumvent this problem.

1 answer

  • answered 2022-05-06 18:34 anubhava

    Problem is in your # Remove .php extension since it is rewriting any non-file request to an equivalent .php file without checking for existence of .php file.

    You can try this code to get this working:

    # Error document handling
    ErrorDocument 404 https://landon.pw/404
    ErrorDocument 403 https://landon.pw/404
    
    Options -Indexes
    # Index.php default 
    DirectoryIndex index.php
    
    RewriteEngine On
    
    # Force HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    
    # Remove .php extension
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    Make sure you clear your browser cache before testing this change.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum