PHP - Display a 404 Error without redirecting to another page

后端 未结 6 1550
天涯浪人
天涯浪人 2020-12-05 05:38

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

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 06:40

    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...

    • Your condition can be as complicated as you can code: check authentication, check for permanent redirects, maybe you want to expire content automatically? Etc., etc..
    • Search your DB for explode('/', $_SERVER['PHP_SELF']), and then display a list of those matched results under the header "Maybe this is what you were looking for?"
    • Respond to user-level events: Is it a 404 because the page was moved? Then handle a redirect. Is it a 404 because a moderator deleted it and it was the user's post? Tell the user a moderator deleted their post. Etc., etc..
    • Make API calls, dynamic code, etc., etc., the possibilities are there.

提交回复
热议问题