简体   繁体   中英

Custom 404 page and send user to it

So my .htaccess-file looks like this

<IfModule mod_rewrite.c>
Options +FollowSymLinks -    MultiViews
RewriteEngine on

ErrorDocument 404 404.php

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]*)$ $1.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ profile.php?username=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)$ profile.php?username=$1&page=$2 [L]
</IfModule>

But when I for instance go to 127.0.0.1/random it actually goes to 127.0.0.1/profile.php?username=random which is understandable so that is why I have a piece of code on profile.php to generate a 404 error if the user doesn't exist

if ($User == NULL) { header("HTTP/1.0 404 Not Found"); }

But still it loads the profile and does not go to the 404 error. I have tried with header('Location: index'); and then it redirects to index

What am I missing to get it to generate 404?

This response has useful information https://stackoverflow.com/a/437705/1231563 it basically states that once the server starts processing you code it will not display the server default 404 page. Though it will set the response code to 404 (which is essentially invisible to the user). However you have your 404 errors going to 404.php in your .htaccess so just use

header('Location: /404.php');

to direct to the 404 php page you have setup.

To show a 404 page without having to redirect to www.example.com/404.php:

if ($User == NULL) 
{ 
    //this will set the 404 header
    header("HTTP/1.0 404 Not Found");

    //this will load the 404 page
    include '/404.html';

}
else 
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM