I have a catchall .htaccess directive like this:

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L]

Anything that doesn't exist and the URL is rewritten back to the index page. This is fine, however I want the header to be sent a 404 instead of a 200. How would I do this?


I think the only way to do so is using ErrorDocument directive:

ErrorDocument 404 index.php

because with RewriteRule you are "masking" the error serving another page to the request.

Yet you must know that ErrorDocument 404 won't change the URL of the page, thus you will have your homepage on a wrong URL.

  • 1
    I had to use /index.php instead of index.php but that worked. That makes more sense now. Thanks Dec 1 '11 at 20:48
  • @Jakobud If it worked mark the question as answered ...
    – Matteo
    Feb 19 '14 at 10:55
  • "you will have your homepage on a wrong URL" - which is, incidentally, what the code in the question would do as well (internal rewrite).
    – MrWhite
    Feb 19 '14 at 14:54

Your original rewrite rule will work. You just need to modify index.php to return a 404. You just need to include this line at the top

 header("Status: 404 Not Found");

At that point, your PHP script will be responsible for writing the content of the error page. You will have implemented a custom 404.

  • Although you'd probably want to do this conditionally in the case of index.php. (Which you could easily do based on the URL.)
    – MrWhite
    Feb 19 '14 at 14:53

A 404 is a dead-end, so you can not send a 404 and redirect unless you use a piece of JS on a 404 page, but I hate those "you will be redirected shortly..." pages.

My solution does not do exactly what you ask but you could do a lot more in the 404.php file.


in .htaccess:

ErrorDocument 404 /404.php

in 404.php:

// Redirect and send 301 header (a redirect defaults to a 302)
header('Location: http://www.example.com/', TRUE, 301);
  • Not sure of the reasoning behind your "solution"? The 404 would seem to be completely superfluous in your example. As you state in your first line "you can not send a 404 and redirect" - you seem to have demonstrated this in your example?
    – MrWhite
    Feb 19 '14 at 15:06
  • Although the server is handling the 404 as a 404 in my solution, the browser is sent a 301 header as a result of the PHP header() function. The reason for using ErrorDocument 404 rather than a rewrite in my case was to do stuff in the 404.php file based on the request, I may want to redirect in some cases, and in other cases I may want to display a 404 page (which would have the 404 header).
    – Duncanmoo
    Feb 20 '14 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.