Redirect requests for files & folders which dont exist with .htaccess

Normally if a visitor requests a file or folder which doesn’t exist your web server will respond with a 404 file not found error message, this isn’t the best looking error message and so it’s common to setup a redirect so instead of the web server showing the default page you can use a custom page which normally fits in with your websites template.

The htaccess is a powerful file and any modifications can stop a website from working correctly. If you receive 500 error messages after modifications you have done something wrong and should revert to a backup.

For example if you go to the following URL on my website you will receive a 404 error message but it is within the normally style of my website, if the redirect wasn’t present you would receive an empty white page with text telling you the file wasn’t found.

http://shanerutter.co.uk/moo

We will be using the .htaccess file which is part of the Apache web server to setup this redirect. You can read about this file here.

http://shanerutter.co.uk/2011/07/31/apache-htaccess-file/

HTaccess

The follow code needs to be placed into your .htaccess file there is two versions of this code please see the differences below. These redirects will only occur if the requests file or folder doesn’t exist. Simply replace http://newdomain.com with the domain you want to redirect to.

Example 1

Domain: http://origionaldomain.com/moo
Redirects to: http://newdomain.com/moo

Example 2

Domain: http://origionaldomain.com/moo
Redirects to: http://newdomain.com

Extra

The two examples above require specifying the domain you wish to redirect to but in some occurrences you may not want this especially if you’re installing on multiple domains as the two examples above will need adjusted on a per domain basis to work correctly. The following is the same as example 2 but it redirects to the websites root directory and so you don’t have to specify a domain.

For example this will redirect any requests to http://domain.com/my_fake_file.txt to http://domain.com/ as long as my_fake_file.txt doesn’t exist.

Remove Query String

It has come to my attention that the redirects will still contain the query string so a request to http://mydomain.com/fake_file.php?action=123 would redirect to http://mydomain.com/action=123, to remove the query string simply add a ? to the end of the redirect location. Below is an example using the example code above.

Leave a Reply

twenty − 20 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Next ArticlePinning Eclipse to the taskbar with Windows 7