开发者

using header() on htaccess for 404 not found

开发者 https://www.devze.com 2023-04-04 04:38 出处:网络
Some of web pages are actually contained in my database. I have the htaccess with the following ErrorDocument 404 /error404.php

Some of web pages are actually contained in my database. I have the htaccess with the following

ErrorDocument 404 /error404.php

My error404 do a require("checkdb.php"); which check if the filename is represented in MySQL db. If so, I want to return 200 OK and spit out the content. If not, I want to spit out that 404

My problem is I'm stuck with 404. While my page is properly displayed, it won't get picked up by search engine and the google+ doesn't work ha开发者_JAVA百科s it does a check for the page and it gets 404.

I've added

header('HTTP/1.1 200 OK'); 

right after a check in the database (no html code has been displayed yet), but I get the

Warning. Cannot modify header information - headers already sent by ....

Even if I move that header() right at the beginning of /error404.php I still get that error. It sounds like Apache will return that 404 first and then call /error404.php

What can I do to properly fix this? Thanks very much in advance!


When Apache sends the document specified by ErrorDocument, it is not serving it as a regular page, and has already sent the 404 headers. Instead of using the ErrorDocument directive in Apache, you should instead use your PHP script to check first if the document exists, and if it does, display it. If it does not exist, then PHP sends the 404 error header itself.

The following does not take place in error404.php, but rather in a normal script like index.php:

// Do whatever you're doing to check
require("checkdb.php");

// If the check fails, PHP sends the 404:
header("HTTP/1.0 404 Not Found");
// Then display your custom error document with PHP
// You can display the other contents of error404.php
echo "Oops, page wasn't found!";
exit();

And remove the ErrorDocument directive from your Apache configuration.


The header line needs to be before any output. Without some code, there is no way we can point out where the output is coming from.

0

精彩评论

暂无评论...
验证码 换一张
取 消