[英]PHP - Load 404 page for non existing articles wihout changing URL
我知道在這方面有很多類似的問題,我已經閱讀了它們,但沒有它們沒有用。 我想在我的網站上訪問不存在的動態網址時顯示404頁面,但不更改網址。 例如:
https://www.trvme.com/destinations/corbett
很好。 但是,如果我輸入一個無效的鏈接,如
https://www.trvme.com/destinations/corbetts
我得到瀏覽器的404錯誤,但我沒有看到我的404頁面。 這是我在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();
}
和htaccess
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
我不想使用header('location:message.php?id=2');
在PHP中因為這會改變URL。 我從URL獲得了404代碼,但htaccess似乎沒有完成它的工作。
我也不能用
http_response_code(404);
include 'message.php';
因為它會拋出會話已經開始的各種錯誤,並且已經定義了常量。 這似乎不是一個優雅的解決方案。
編輯:
鏈接問題中的代碼對我不起作用。 如果我在目標規則上面添加代碼,現有的合法頁面也會轉到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]
如果我之后把它放,它就不起作用,因為目的地規則接管了
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.