简体   繁体   中英

If a web page doesn't exist, what headers should I return?

What should happen when a page doesn't exist on your site? If I have a custom error page set up in my .htaccess, I get a 302 temporary redirect to my 404 page (where I send 404 headers). Is this how it should work? Or should I do a 301 permanent redirect to the error page? I'm using php and Apache.

If it never existed, you should send 404 Not Found .

If it used to exist, but doesn't any more, you should send 410 Gone .

Set up your server to send the error response directly.

You shouldn't redirect to an error page. That essentially means the conversation would go:

  • Browser: Can I have /foo?
  • Server: You can find /foo at /bar!
  • Browser: Can I have /bar then?
  • Server: I can't find /bar.

Bait and switch is never nice.

The non-existent page has not "temporarily moved" (301) or "permanently moved" (302) to a page about the file not existing, it doesn't exist. The correct header to send is a 404, not anything else.

Don't redirect anywhere, instead serve your "file not found" page content at the URL that was requested.

If you got a static error page, say 404.html, that apache shows when a page is not found, and you need to be able to serve 404 pages for your dynamic pages as well, you can do that by sending the 404 header from PHP and feed the error page as well:

<?php
header("HTTP/1.0 404 Not Found");
readfile("404.html");
?>

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