[英]PHP - Load 404 page for non existing articles wihout changing URL
I know there are many similar questions on this and I've read them and no they didn't work. 我知道在这方面有很多类似的问题,我已经阅读了它们,但没有它们没有用。 I want to show 404 page when a non existing dynamic url is accessed on my website but without changing the url. 我想在我的网站上访问不存在的动态网址时显示404页面,但不更改网址。 For example: 例如:
https://www.trvme.com/destinations/corbett
is fine. 很好。 But if I enter an invalid link like 但是,如果我输入一个无效的链接,如
https://www.trvme.com/destinations/corbetts
I get browser's 404 error but I don't see my 404 page. 我得到浏览器的404错误,但我没有看到我的404页面。 Here's the code I have in PHP 这是我在PHP中的代码
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();
}
And htaccess 和htaccess
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
I don't want to use header('location:message.php?id=2');
我不想使用header('location:message.php?id=2');
in php because that would change the URL. 在PHP中因为这会改变URL。 I'm getting 404 code from the URL but htaccess doesn't seem to be doing its job. 我从URL获得了404代码,但htaccess似乎没有完成它的工作。
I also can't use 我也不能用
http_response_code(404);
include 'message.php';
because it throws all kinds of errors like session has started already and constants have been defined already. 因为它会抛出会话已经开始的各种错误,并且已经定义了常量。 That doesn't seem like an elegant solution. 这似乎不是一个优雅的解决方案。
Edit: 编辑:
The code in the linked question doesn't work for me. 链接问题中的代码对我不起作用。 If I add the code above the destinations rule, the existing, legitimate pages also go to 404 because there's no actual file or directory, these are dynamic urls. 如果我在目标规则上面添加代码,现有的合法页面也会转到404,因为没有实际的文件或目录,这些是动态URL。
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]
If I put it afterwards, it just doesn't work because the destinations rule takes over 如果我之后把它放,它就不起作用,因为目的地规则接管了
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]
if you want a specific 404 you need to catch it or create the 404 HTML that is loaded within apache. 如果你想要一个特定的404,你需要捕获它或创建在apache中加载的404 HTML。
look at: catching all invalid URLs 看看: 抓住所有无效的网址
They've suggested using the ErrorDocument within the apache. 他们建议在apache中使用ErrorDocument。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.