Behseini
Behseini

Reputation: 6330

How to redirect to 404 but keep wrong URL on address bar using .htaccess

Using .htaccess, I am trying to redirect to 404 with following rules on my website which is working fine

RewriteEngine ON
ErrorDocument 404 thedomain.com/404
RewriteCond %{REQUEST_URI} !\.php/?$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

but as it is expected this is changing/redirecting the URL as well. For example with not having a file name called dummy.php the URL will redirect to thedomain.com/404.

How can I can keep the existing URL (thedomain.com/dummy) and redirect to thedomain.com/404 like what is happening in WordPress 404 pages.

enter image description here

Upvotes: 1

Views: 2923

Answers (1)

anubhava
anubhava

Reputation: 786001

Have your .htaccess code like this:

RewriteEngine On

ErrorDocument 404 /2021/404.php

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

When you have absolute URL in ErrorDocument 404 it will perform full redirect. However using a relative URL will only do an internal rewrite to prevent URL changing in browser.

Make sure to clear your browser cache before testing.

Upvotes: 2

Related Questions