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. 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. Here's the code I have in 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
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');
in php because that would change the URL. I'm getting 404 code from the URL but htaccess doesn't seem to be doing its job.
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.
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.
look at: catching all invalid URLs
They've suggested using the ErrorDocument within the apache.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.