1

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • Does this answer your question? [.htaccess redirect to 404 page RewriteRule](https://stackoverflow.com/questions/7733647/htaccess-redirect-to-404-page-rewriterule) – Ainz Jan 13 '21 at 06:28
  • 1
    Thanks for quick reply but the URL still changing to 404. I added up the `RedirectMatch 404 ^/abc/.*$` to the end of rules, by the way – Behseini Jan 13 '21 at 06:30

1 Answers1

2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Same old! URL also is changing – Behseini Jan 13 '21 at 06:33
  • I just copied everything from here – Behseini Jan 13 '21 at 06:35
  • I am also getting `Not Found` after clearing cache .`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.` – Behseini Jan 13 '21 at 06:39
  • I even check it in another browser and is same. Yes `thedomain.com` is a folder in `DocumentRoot` BUT I have the `.htaccess` inside this folder – Behseini Jan 13 '21 at 06:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227252/discussion-between-anubhava-and-behseini). – anubhava Jan 13 '21 at 06:49