gpt4 book ai didi

php - 在 htaccess 上使用 header() 找不到 404

转载 作者:行者123 更新时间:2023-11-29 14:43:58 24 4
gpt4 key购买 nike

一些网页实际上包含在我的数据库中。我的 htaccess 具有以下内容

ErrorDocument 404 /error404.php

我的 error404 执行了 require("checkdb.php");它检查文件名是否在 MySQL 数据库中表示。如果是的话,我想返回200 OK,并吐出内容。如果没有的话我想吐槽那个404

我的问题是我被 404 困住了。虽然我的页面正确显示,但搜索引擎不会拾取它,并且 google+ 无法工作(如果它检查页面并得到 404)。

我已经添加

header('HTTP/1.1 200 OK'); 

在检查数据库后(尚未显示 html 代码),但我得到了

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

即使我将 header() 移到 /error404.php 的开头,我仍然会收到该错误。听起来 Apache 会先返回 404,然后调用 /error404.php

我该怎么做才能正确解决这个问题?预先非常感谢!

最佳答案

当 Apache 发送由 ErrorDocument 指定的文档时,它不会将其作为常规页面提供服务,并且已经发送了 404 header 。您应该使用 PHP 脚本首先检查文档是否存在,而不是在 Apache 中使用 ErrorDocument 指令,如果存在,则显示它。如果不存在,则 PHP 自行发送 404 错误 header 。

以下内容不会发生在 error404.php 中,而是发生在像 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();

并从 Apache 配置中删除 ErrorDocument 指令。

关于php - 在 htaccess 上使用 header() 找不到 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com