php.htaccesshttp-status-code-404custom-error-pages

htaccess ErrorDocument 404 only works for subdirectory


I want to redirect user to custom 404 page.

<IfModule mod_rewrite.c>
RewriteEngine On

# If the request is for a directory, do nothing
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# If the request is for an existing file, do nothing
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Append ".php" extension to URLs without an extension
RewriteCond %{REQUEST_URI} !\.(html?|php)$
RewriteRule ^([^/]+)/$ $1.php

# Append ".php" extension to URLs with two path segments
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php

# If the request doesn't end with a slash or an extension, redirect to a trailing slash
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

# Custom 404 error handling
ErrorDocument 404 /error
</IfModule>

This is the code I configure in my .htaccess. This code works only for subdirectory for example https://example.com/about/abc but not working for link example https://example.com/abc (Only show an error message "File not found."). Please tell me what should I do to make the redirect works for all 404 page. Thanks is advance.


Solution

  • <IfModule mod_rewrite.c>
    RewriteEngine On
    
    # If the request is for a directory, do nothing
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    # If the request is for an existing file, do nothing
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]
    
    # Append ".php" extension to URLs without an extension
    RewriteCond %{REQUEST_URI} !\.(html?|php)$
    RewriteRule ^([^/]+)/$ $1.php
    
    # Append ".php" extension to URLs with two path segments
    RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
    
    # If the request doesn't end with a slash or an extension, redirect to a trailing slash
    RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
    RewriteRule (.*)$ /$1/ [R=301,L]
    
    # Custom 404 error handling
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /error.php?request=$1 [L,QSA]
    </IfModule>
    

    A custom 404 error handling rule has been added using the RewriteRule directive. This rule checks if the requested file or directory does not exist (!-f and !-d). If this condition is met, the request is rewritten to error.php file, passing the original request URI as a query parameter (request=$1)

    You will need to create the error.php file in your document root to handle the custom 404 error.

    <?php
    $request = $_GET['request'];
    header('HTTP/1.1 404 Not Found');
    echo "The requested URL '$request' was not found on this server.";