Skip to content
Advertisement

Current setting up for apache/php will always return a 200 page instead of 404

UPDATE: I added a 404 error document:

<IfModule mod_rewrite.c>
RewriteEngine on
ErrorDocument 404 /new404.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</IfModule>

But nothing has changed.

I have a problem with an apache snippet:

RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

in

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</IfModule>

I created to obtain an URL like this:

http://localhost:8888/en
http://localhost:8888/en/team
http://localhost:8888/en/anything

And I called my PHP file like this:

team-en.html.php
anything-en.html.php

This because I have different languages.

now, that’s my PHP file to display them:

$path = isset($_GET['path']) ? $_GET['path'] : false;
$path = strtolower($path);
$path = preg_replace("/[^a-z-/]/", '', $path);
$parts = explode("/", $path);


if (is_array($parts) && isset($parts[1])) {
    if (file_exists(__DIR__ . '/processors/' . $parts[1] . '.php')) {
        $processor = $parts[1];
    }
    if (file_exists(__DIR__ . '/pages/' . $parts[1] . '-'. $language .'.html.php')) {
        
        $page = $parts[1];
    }
}

Where languages variable is:

$language = 'en';

$languages = [];
$languages[] = 'en';
$languages[] = 'nl';
$languages[] = 'fr';

Now, this won’t return a 404 page for some reason and will return only a 200 header response.

I’m wondering if anyone has experience in setting up a 404-page system, I read a lot of tutorials but none of them gave me a satisfying answer.

Thank you in advance

Advertisement

Answer

The rewrite rule matches on all routes. There’s no way that Apache can throw a 404 error, as it does not know what your application is doing.

You need to check whether such an error should be thrown in your application itself, within PHP code. If the files within the subfolders are the proper condition for this, you could write:

if (is_array($parts) && isset($parts[1])) {
    if (file_exists(__DIR__ . '/processors/' . $parts[1] . '.php')) {
        $processor = $parts[1];
    }
    if (file_exists(__DIR__ . '/pages/' . $parts[1] . '-'. $language .'.html.php')) {
        $page = $parts[1];
    } else {
        http_response_code(404);
        die();
    }       
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement