Mobile app version of vmapp.org
Login or Join
Holmes151

: .htaccess - if the file doesn't exist, rewrite to index.php but send 404 instead of 200 I have a catchall .htaccess directive like this: RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME}

@Holmes151

Posted in: #Htaccess

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?

10.03% popularity Vote Up Vote Down


Login to follow query

More posts by @Holmes151

3 Comments

Sorted by latest first Latest Oldest Best

 

@Heady270

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.

10% popularity Vote Up Vote Down


 

@Sue5673885

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.

Solution:

in .htaccess:

ErrorDocument 404 /404.php


in 404.php:

<?php
// Redirect and send 301 header (a redirect defaults to a 302)
header('Location: www.example.com/', TRUE, 301);

10% popularity Vote Up Vote Down


 

@Sent6035632

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.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme