Automatically redirect non-existing pages to the home page in Apache

How to configure Apache so that requests for non-existing pages are redirected to the home page.

In some occasions, you don't want people to get 404 messages when they surf to pages or folders that don't exist on your web server (anymore). For example, when you have Basic Authentication, end users only get the pop-up that requests them to authenticate when they surf to an existing page or folder. The security impact of this is that when attackers perform a brute force scan on your file server, they can easily detect whether pages and folders exist or not:

  • When pages exist, they get the pop-up that requests them to authenticate themselves;
  • When pages don't exist, they just get a 404 error page.

Therefore, what we want to do is to configure the web server so that when somebody requests a non-existing page, they will get the home page served to them. This means that no matter what URL attackers will try out, they will always get a pop-up that asks them to authenticate themselves.

Now how can we easily do this? By using the Rewrite module from Apache (mod_rewrite). Chances are big that you already have this module enabled. The best part is that you can put the following code into a .htaccess file. So even if you rent hosting somewhere on the Internet, you can easily implement this.

If you copy/paste the following code into a .htaccess file, all requests for non-existing files or folders will return the contents of your index.php file.

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

The meaning of every line is the following:

  •   RewriteEngine on: Enable the runtime rewriting engine.
  •   RewriteCond %{REQUEST_FILENAME} !-f: The rewriting will take place is the requested filename is not a regular file or if the file doesn't exist.
  •   RewriteCond %{REQUEST_FILENAME} !-d: The rewriting will take place is the requested filename is not directory or if the directory doesn't exist.
  •   RewriteRule ^(.*)$ / [L,QSA]: If the above conditions both match (the requested file isn't a file, isn't a directory, and doesn't exist) then the URL will be rewritten to the root of your website. The "L" means that the rewriting process should stop immediately after this rule has been applied and the "QSA" means that any query string from the original request URL must be appended to the rewrite target.

Tags: 

You might also be interested in...