Use .htaccess to set 404 error document located in the same folder

Viewed 9031

So... i am trying to set the path to an error document located in the same directory as the .htaccess (located in the WEBSITE "root") like this:

       ErrorDocument 404 404.php

However instead of showing the webpage...it just writes 404.php on the screen. I can't use absolute paths like:

       ErrorDocument 404 /404.php

Because i am not doing the website for me and i do not know the absolute path of the folder the website will be stored on...

My question is: Can i set relative paths in the .htaccess document rather than absolute ones? (and if yes...how?)

3 Answers

ErrorDocument paths are relative to the DocumentRoot server setting, which is usually found in /etc/apache2/sites-enabled/000-default.conf This is how it looks in my file:

<VirtualHost *:80>   <---------------- VirtualHost on port 80 is generally internet traffic
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/   <-------- this is what we're looking at
</VirtualHost>

Note that the DocumentRoot set in this file is absolute in the filesystem - var is in the bottom level folder /.

So my .htaccess file resides in /var/www/myapp/.htaccess, meaning that the .htaccess file exists one directory down from DocumentRoot (which is set to /var/www/). So in order to have my ErrorDocument 404 served from /var/www/myapp/errordocs/404.html, I need to set, in my .htaccess, the following:

ErrorDocument 404 /myapp/customErrorPages/custom_404.html

Note that even though the .htaccess file resides in the myapp folder, I still need to include the /myapp/ in the path, as the path is relative to the DocumentRoot as defined in /etc/apache2/sites-enabled/000-default.conf

Also note that the path must start with a / in order for apache to read it as a path. Setting "myapp/customErrorPages/custom_404.html" (without the leading /) will result in just that string being printed instead of a document being served.

Pretty confusing if you don't have knowledge of directory paths in linux and configuration files in apache, but keep poking around you'll get it ;)

Related