All Linux HowTo's Security HowTo's

Secure your Web Site with a .htaccess file

Share This:

A simple way to secure your website is with a “.htaccess” file. When i say “secure” i simply mean the website (or sub directory) will require a password to gain access. This is great for when you are still developing the website or when you have a directory within the website such as “www.agix.com.au/secured” that you want to protect.

This HowTo directly applies to Redhat and CentOS servers but with minor changes will work for other distro’s too.

TIP: Ask for password over HTTPS (ssl). HTTP sends password in clear-text.

Challenge: Try to get Apache to authenticate to LDAP so your staff can have restricted access without adding them manually to the password file.

Challenge: Try forcing visitors to SSL (https) before asking for their login credentials. You can do that with the “.htaccess” file too.

In my example below we’re using the root “/var/www/html/website1” and we’re going to limit access to the sub-directory “/var/www/html/website1/secured”. We’re going to create two users: “admin” and “developer”. Both will have access.

htpasswd -c /etc/httpd/website1.password admin
htpasswd /etc/httpd/website1.password developer

Create the “.htaccess” file in the directory “/var/www/html/website1/secured”.

vi /var/www/html/website1/secured/.htaccess

And add the following to your “.htaccess” file:

# Limit access to the /secured section of the website.
AuthUserFile /etc/httpd/website1.password
AuthName "Secured by AGIX" 
AuthType Basic
require valid-user  

TIP: If you already have content in your “.htaccess” file, you can add the above to the end of the existing content.

You don’t need to restart Apache to have this take effect. However, there is a possibility that Apache’s configuration doesn’t allow overrides. If the “.htaccess” file doesn’t work then try the following.

Edit your Apache’s main configuration file (where the website “website1” is configured) and ensure that it has the “AllowOverride” option set to the following:

AllowOverride All

For example:

<VirtualHost *:80>
 <Directory /var/www/html/website1>
 AllowOverride All
 </Directory>
 ServerAdmin support@agix.local
 DocumentRoot /var/www/html/website1/
 ServerName www.website1.example.com
 ServerAlias website1.example.com
 ErrorLog logs/www.website1.example.com.log
 CustomLog logs/www.website1.example.com.log common
</VirtualHost>

Changes to the Apache config files require a reload (or restart) of Apache.

You can research the “AllowOverride” here: “http://httpd.apache.org/docs/current/mod/core.html#allowoverride”.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *