I want to display a 404 Error if a user reaches a page that exists but I don\'t want him/her to see.
I don\'t want to do redirect (that would cause the address bar t
These are all great answers for redirecting to 404 error, for a single page. Here's a solution that will allow you to test a condition and redirect for any script on your site.
Write up a .htaccess
file, with the rewrite rules, and using [QSA,NC,L]
to maintain the page location and the header post/get arguments...
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,NC,L]
This will cause every page to redirect to ./index.php
(feel free to rename this if you're already using an index.php
). The URL will not be changed. Then, in index.php
, check some condition, and if passes, include the $_SERVER
variable indicating the script, otherwise, do a custom 404. This means you can simply control the exception handling in index.php
with...
$someNon404Condition = file_exists($_SERVER['PHP_SELF']);
if ($someNon404Condition) {
include($_SERVER['PHP_SELF']); // do the stuff
} else {
print("404! Why are you trying to access " . $_SERVER['PHP_SELF'] . "?");
}
This lets you do tons of other things, too! Forget a static 404.html page, with a dynamic one you can...
explode('/', $_SERVER['PHP_SELF'])
, and then display a list of those matched results under the header "Maybe this is what you were looking for?"