Lara Ch
Lara Ch

Reputation: 165

Redirect into my designed 404 page if URL does not exist

I want to create a PHP script that allows me to redirect a user into a 404 page (designed by me) to tell him that the url request by him does not exist. Currently I am working offline, so my server folder is www/myproject/pages.php and if a user typed localhost/myproject/files.php per example, I want to take him into a 404 error page.

I know I should use something like header('HTTP/1.1 404 Not Found'); but I don't know how to make the condition:

if(url does not exist in my working folder).

I've tried this script:

$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;
}

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

Upvotes: 1

Views: 6523

Answers (1)

NotJeeves
NotJeeves

Reputation: 43

You can do routing in PHP as well. Something like https://github.com/nikic/FastRoute if you want. Any undefined routes(pages) can be pushed to a 404 page.

Alternatively use your .htaccess or nginx config to redirect pages that don't exist.

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]

Upvotes: 3

Related Questions