Simple .htaccess content protection

01.Oct.2010

So, let’s say you are about to launch your new website. You have written it and tested in localhost, and it is time to go live! Only… not in the public yet. You want to adjust some more things, and check if your website is working correctly, and you don’t want users to see errors on your website.

There is a simple way of protecting your content with password, for every user that has not verified as someone who knows password. By using this snippet, you will be able to hide your content from all people that you don’t want to give access.

If user is not on the list of allowed IP addresses, it will be redirected to /login/index.php.
If user knows secret code, his IP will be added into .htaccess.ip-restriction file, and then will be created new .htaccess file.

/.htaccess = /.htaccess.production + /.htaccess.ip-restriction

Files

  • /.htaccess
  • /.htaccess.production
  • /.htaccess.ip-restriction
  • /login/.htaccess
  • /login/index.php

/.htaccess

1
2
3
ErrorDocument 403 /login/index.php
Order Deny,Allow
Deny from all

/.htaccess.production

1
#your code here

/.htaccess.ip-restriction

1
2
3
4
5
ErrorDocument 403 /login/index.php
 
Order Deny,Allow
Deny from all
Allow from xxx.xxx.xxx.xxx  # IP you would like to initially allow access

/login/.htaccess

1
2
Order Allow,Deny
Allow from all

/login/index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
    function allow_by_ip($ip) {
        error_log("nAllow from $ip # " . $_POST['password']. "n", 3, $_SERVER['DOCUMENT_ROOT'] . "/.htaccess.ip-restriction");
        $htaccess_ip = (array) file($_SERVER['DOCUMENT_ROOT'] . "/.htaccess.ip-restriction");
        $htaccess_production = (array) file($_SERVER['DOCUMENT_ROOT'] . "/.htaccess.production");
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/.htaccess", array_merge($htaccess_ip, $htaccess_production));
    }
// if password is correct, add users IP into .htaccess
    if($_POST['password'] == 'secret-code') {
        allow_by_ip($_SERVER['REMOTE_ADDR']);
        header("Location: /");
    } else {
?>
<form action="/login/index.php" method="post">
    <input id="password" type="password" name="password" />
    <input id="submit" type="submit" name="submit" value="submit" />
</form>
<?php
    }
?>

If you want to remove protection, just delete .htaccess file and rename .htaccess-production file to .htaccess.

Have a good luck testing your website live without letting anybody know!