Home > Blockchain >  redirect url ends with .php page to custom 404 page using htaccess caused the custom 404 page broke
redirect url ends with .php page to custom 404 page using htaccess caused the custom 404 page broke

Time:09-27

RewriteEngine On
ErrorDocument 404 /exception/404.php
//if url ends with .php/ , show custom 404 page
RewriteRule .php/$ - [R=404,L]
//this line caused the custom 404 page broken
RewriteRule .php$ - [R=404,L]

before I added line 4: speedcubing.top/index.php

(show the index page)

speedcubing.top/index.php/

(show custom 404 page)

after I added line 4: speedcubing.top/index.php speedcubing.top/index.php/

they both showing:

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

CodePudding user response:

ErrorDocument directive and RewriteRule directive are from different Apache modules that run at different times. Hence setting R=404 doesn't cause Apache to invoke ErrorDocument handler and it ends up showing default 404 Apache handler.

You should add this line in your /exception/404.php to set a custom http response code:

<?php
http_response_code(404);
// rest of the code
?>

And have your .htaccess code like this:

ErrorDocument 404 /exception/404.php

RewriteEngine On

# if url ends with .php or .php/, show custom 404 page
RewriteCond %{REQUEST_URI} !^/exception/404\.php$ [NC]
RewriteRule \.php/?$ exception/404.php [NC,L]
  • Related