Redirect to custom 404-page doesn't work on localhost (Apache)

Viewed 48

I have a .htaccess-file that has the directives as listed below. The first three lines are used to provide custom error pages for 403, 404 and 429.

ErrorDocument 404 /404.php
ErrorDocument 403 /403.php
ErrorDocument 429 /429.php

DirectoryIndex maintenance.html index.php index.html index.htm home.html 
#Rewrite everything to https
<If "%{HTTP_HOST} != 'localhost'">
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>
<Else>
    # local configuration 
    # nothing special here...
</Else>

This works perfectly fine when I publish to my website. When trying to open a non-existing page such as mysite.com/wrongpage.php the custom 404.php page is showed.

But when I try to do the same thing on localhost when entering localhost/wrongpage.php. It simply shows the browsers default 404 message. The 404.php page exists, but isn't used as expected.

I am not very good at how to work with the .htaccess file, but perhaps you can help me understand why it won't work on localhost?

1 Answers

This suggests you've not enabled .htaccess overrides on your local development server. .htaccess files are essentially disabled so the directives are not doing anything.

You need to set the AllowOverride directive in the appropriate <Directory> container in the server config (or <VirtualHost> container). By "appropriate" I mean the specific <Directory> container that targets your document root directory, not the entire server (which should remain AllowOverride None).

For example:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        Require all granted

        # Enable .htaccess overrides
        AllowOverride All

    </Directory>
</VirtualHost>

And restart Apache.

Reference:

Related