PHP-加载404页面以获取不存在的不更改URL的文章

时间:2019-03-26 12:28:11

标签: php .htaccess

我知道对此有很多类似的问题,我已经阅读了,没有,它们没有起作用。我想在我的网站上访问不存在的动态URL而不更改URL时显示404页面。例如:

URLEncoder.encode(deviceid, "utf-8")

很好。但是,如果我输入了无效的链接

https://www.trvme.com/destinations/corbett

我收到浏览器的404错误,但看不到404页面。 404 error 这是我在PHP中拥有的代码

https://www.trvme.com/destinations/corbetts

还有htaccess

if(isset($_GET['destId'])){
    $link = mysqli_real_escape_string($connect, $_GET['destId']);
    $thisPage = 'destinations/'.$link;

    $query = "SELECT * FROM `destinations` WHERE `link` = '$link' AND `active` = 1 AND `delete` = 0";
    $destinationsQuery = mysqli_query($connect, $query);
    if(mysqli_num_rows($destinationsQuery)!=0){
        // do stuff
    } else {
        http_response_code(404);
        exit();
    }
} else {
    http_response_code(404);
    exit();
}

我不想在php中使用RewriteEngine On ErrorDocument 404 /message.php?id=2 RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L] ,因为那样会更改URL。我从URL中获取404代码,但htaccess似乎没有完成其工作。

我也不能使用

header('location:message.php?id=2');

因为它会引发各种错误,例如会话已经开始并且常量已经定义。这似乎不是一个很好的解决方案。

编辑:

链接的问题中的代码对我不起作用。如果我将代码添加到destinations规则之上,则由于没有实际的文件或目录,这些合法的页面也会转到404,这是动态url。

http_response_code(404);
include 'message.php';

如果我把它放在后面,那是行不通的,因为目的地规则接管了

RewriteEngine On

ErrorDocument 404 /message.php?id=2

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]

RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]

1 个答案:

答案 0 :(得分:0)

如果您想要特定的404,则需要捕获它或创建apache中加载的404 HTML。

查看:catching all invalid URLs

他们建议在Apache中使用ErrorDocument。