简体   繁体   中英

Correct way to display 404 page in PHP?

So currently when a user loads a page that doesn't exist, or something goes wrong - I redirect users to a 404 page using header in PHP:

header('Location: www.website.com/404'); //This is simplified intentionally

This page displays a 404 icon with a link back to the homepage, and some other information

Recently in Google Webmaster tools I've been getting a few messages that I'm not returning a 404 page correctly.

Should I be returning http_response_code when displaying the 404 page? Or should I be handling 404 differently?

You can use this ... You need to make .htaccess on you root folder

.htaccess

Redirect 301 /index.html http://example.com/newdirectory/

any internet crawler/spider or tools have 404 status code as not found so you better output the status code so the page will be known for what it is

you can do that by outputting a raw header like this

<?php
if(!authorized){
  header("HTTP/1.0 404 Not Found");
  header("Location: http://www.website.com/404");
}
echo "*OUTPUT*";
?>

but this alone causes a security issue because the rest of the pages output is being output and is still executed:

$ curl http://localhost/stackoverflow/404.php
*OUTPUT*

so you should exit after redirecting, so the code will be like this:

<?php
if(!authorized){
  header("HTTP/1.0 404 Not Found");
  header("Location: http://www.website.com/404");
  exit;
}
echo "*OUTPUT*";
?>

and now it will stop executing after the redirect

$ curl http://localhost/stackoverflow/404.php
$

and for more safety use htaccess.

htaccess 404 Error Code

Once you have your 404 page setup, all you need to do is send visitors of incorrect url's to this page. To do this just add the following line to your .htaccess file :

ErrorDocument 404 /404.php

Most often, the .htaccess file will be in the home root public_html folder on your server. This can change, for an example if you run you site or blog out of a specific folder within the public_html.

Alternately, You can place the 404 error template anywhere you want in a folder. For example you could place all error messages in a folder called errormessages refererring the 404 error to the url of the page.

ErrorDocument 404 /errormessages/404.php

That's all there is to it.

Now when a visitor views an incorrect url on your site they will see your custom 404 error message.Its well explained here.

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