How to Protect a Directory using a 301 Redirect via PHP

Many people have asked me recently how to protect a directory on their websites.  In most cases, all they wanted was to stop people being able to browse to the directory and list the files. 

There are many ways of doing this – some fairly easy and some quite complex – and I always recommend using what I think is the simplest of all – an HTTP 301 Redirect via a straightforward PHP file.  OK, so it sounds complex, but bear with me…

Firs of all, decide where you want to redirect the visitor to – usually your homepage.  We’ll assume that your homepage is at http://www.yourdomain.com.

Now, we want to create a text file with the following code:

<?
header( "HTTP/1.1 301 Moved Permanently" );
header( "Status: 301 Moved Permanently" );
header( "Location: http://www.yourdomain.com/" );
exit(0); // This is Optional but suggested, to avoid any accidental output
?>

IMPORTANT: Make sure you don’t leave any blank lines at the top of this file!

Once you’ve created it, save it as index.php and upload it to the directory you wish to protect.  Now, anyone browsing to that directory will be redirected away to your homepage instead of seeing a directory listing.

As a bonus, you might to consider creating a robots.txt file so that Google and the other search engines don’t catalogue your files and make them easily accessible to anyone searching.

For this example, we’ll assume that you have all of your images in a directory called ‘images’ and you want to prevent those files from being indexed and browsed.  First of all, you’d create the index.php file as described above and upload it to the images folder.  Then, create a file called robots.txt containing the following:

User-agent: *
Disallow: /images/

Upload this to the root directory of your server and your images should be nicely shielded.

Please note that neither of these methods will prevent someone who’s intent on copying your files to get at them, but it will keep the casual browser at bay!

 

About The Author

John

John is a Senior Solutions Engineer for a U.S. IT company, specialising in Software Defined IT Infrastructure. He has an extensive background in IT and spends way too much time sitting at his PC's, making videos for himself and other Internet marketers and dreaming of spending more time boating. He's also passionate about Jesus.

Comments are closed.