【问题标题】:Redirect into my designed 404 page if URL does not exist如果 URL 不存在,则重定向到我设计的 404 页面
【发布时间】:2016-08-16 21:59:34
【问题描述】:

我想创建一个 PHP 脚本,允许我将用户重定向到 404 页面(由我设计),告诉他他的 url 请求不存在。目前我正在离线工作,所以我的服务器文件夹是www/myproject/pages.php,如果一个用户输入了localhost/myproject/files.php,我想把他带到一个404错误页面。

我知道我应该使用 header('HTTP/1.1 404 Not Found'); 之类的东西,但我不知道如何创建条件:

如果(我的工作文件夹中不存在 url)。

我试过这个脚本:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

来自this link but still can't know how to add the condition

【问题讨论】:

  • 您的链接指的是完全不同的问题(如何检查 external 网址是否不存在)。您必须修改 .htaccess(或 apache 配置)以在您的站点上重定向 404。见here
  • 谢谢,真的很有帮助

标签: php


【解决方案1】:

您也可以在 PHP 中进行路由。如果您愿意,可以使用 https://github.com/nikic/FastRoute 之类的东西。任何未定义的路由(页面)都可以推送到 404 页面。

或者使用您的 .htaccess 或 nginx 配置来重定向不存在的页面。

nginx

error_page 404 /index.html;

阿帕奇

ErrorDocument 404 /custom_404.html

htaccess

ErrorDocument 404 http://example.com/404/
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

【讨论】:

  • 我在我的 wamp 服务器文件夹中找不到 .htacess
  • 如果不存在,您可以创建一个。有一些关于如何启用它的教程。
  • @LaraCh:你是如何检查 .htaccess 的?它有时是隐藏的。就像您在 cpanel 上由非 root 用户访问它或使用诸如 winSCP 之类的任何工具一样。确保您可以看到隐藏的文件。
猜你喜欢
  • 2014-06-10
  • 1970-01-01
  • 2016-04-04
  • 2023-04-09
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多