如果 URL 不存在,请重定向到我设计的 404 页面


Redirect into my designed 404 page if URL does not exist

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

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

if(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;
}

从此链接,但仍然不知道如何添加条件

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

或者使用您的.htaccess或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]