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

时间:2016-04-23 07:20:52

标签: php

我想创建一个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;
}

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

1 个答案:

答案 0 :(得分:3)

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

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

<强> nginx的

error_page 404 /index.html;

apache

ErrorDocument 404 /custom_404.html

<强> htaccess的

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