Menu

The .htaccess file is a distributed configuration file for Apache that provides a way for you to make changes on a per-directory basis. When placed in a specific directory, the changes dictated by the file only apply to that directory and its sub-directories, enabling the users and not the administrators to configure the behavior of Apache if allowed.

This is especially useful in a shared hosting environment where the average user doesn’t have access to the actual configuration files. If you have access to the configuration files, any change made in the .htaccess file can be made in the main configuration files which is preferable as it provides better performance.

The main configuration file of Apache is the ultimate arbitrator of what is allowable and not allowable for the .htaccess file to control and it will also yield to each directory higher than itself. If you wish for the .htaccess file to be able to change almost anything, you use the directive “AllowOverride All” in the Apache configuration. You can also only grant specific rights like “AuthConfig” to allow the user to password protect specific areas. For example, in the virtual host config or in the main config, you can use the AllowOverride All in the Directory definition.

<Directory “/var/www”>
   AllowOverride All
</Directory>

 

Add Password Authentication

One of the most basic features most people look for is the ability to provide password authentication to a particular directory and doing this is relatively easy. Change the directory to the web accessible directory you want access to. Next, create an .htaccess file with the following information:

AuthType Basic
AuthName “Protected Location, Credentials Please?”
AuthUserFile /var/www/domain.tld/htdocs/protected/.htpasswd
Require user valid-user

Then execute the following command:

htpasswd -c /var/www/domain.tld/htdocs/protected/.htpasswd testuser

At this point it will request you type the password for the user and will create an entry in the .htpasswd file. You only need to use the -c flag when you’re doing the initial creation of the file, after the first time you can simply specify the file name and user to add to it.

If you attempt to access your site now you will be prompted to enter a username and password. Enter the username and password you created in the previous step, and it will allow you access and will not request a username and password again unless you clear the session cache.

Having authentication on the fly is useful, but there are several other variations that can be used to provide easy access from known locations to password protected access from unknown locations. For example, we’ll start with our previous example and add the ability for anyone on the local lan to access it without a password:

AuthType Basic
AuthName “Protected Location, Credentials Please?”
AuthUserFile /var/www/domain.tld/htdocs/protected/.htpasswd
<RequireAll>
   RequireMethod GET POST
   <RequireAny>
       Require ip 192.168.
       Require valid-user
   </RequireAny>
</RequireAll>

Now anyone attempting to access the protected content will have to meet one of two criteria– either A) have access to the 192.168.0.0/16 subnet or B) know the correct username and password.

 

Redirect and Rewrite URLs

The .htaccess file however is not limited to just authentication changes. You can also rewrite URLs and redirect traffic if you wish. For example:

Redirect 301 /old http://www.domain.tld/new

The above code redirects permanent (301) requests to /old to http://www.domain.tld/new. This is often useful if there is a change in the management software on the website, or if a significant change to the layout have been made. That being said, you rarely end up being able to use something as simple as that because you will frequently use query strings in the requests (ie. something following the base URL like: ?app=4&site=domain.tld&ref=9), and to redirect those is a bit more complex. For example:

RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING}    ^article=0001$
RewriteRule ^main.php$ /article1 [R=301,L]

What this says is to redirect any query to http://www.domain.tld/main.php?article=0001 to http://www.domain.tld/article1 and it’s fairly easy to extend that to include part of the rewrite string in the resulting URL allowing you to redirect uniform URLs en-mass to the correct location.

 

Protect Your Images and Bandwidth

I’ll share one more tidbit regarding the .htaccess file. You can also use it to prevent people from hot-linking to your images and stealing your bandwidth.

This doesn’t always work due to needing to make exceptions for browsers that strip out the referer (the misspelling is intentional, it was misspelled in the RFC and has remained the same since.) Nevertheless, the code to do this is fairly simple:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?domain\.tld/ [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ – [F]

What this rule says is for any request that doesn’t originate from my domain, return a forbidden response. You could further modify this to rewrite the URL they are requesting and display the image of your choice. You could also allow blank referrers to access the site resources or deny any specific site you don’t want hot-linking your site specifically, for instance, Facebook or a competitor’s site.

 

Bottom Line

The flexibility the .htaccess file offers is massive and will allow you to write better sites and optimize your existing sites to utilize your incoming links efficiently after a reorganization. The sky’s the limit in terms of flexibility and with a bit of care and work you can create just about any rule set you can imagine.

 

Alex West is currently a Senior Engineer at Pantek. His Linux and open source adventure began by starting a small ISP, and continued for the next 20 years. Alex is involved in large project work including cloud migrations, architecture, and cloud management. His specialization includes small to large scale migrations from heterogeneous environments to secure, manageable, and stable open source platforms. When he isn’t staring at the screen, Alex can be found taking pictures of old buildings, or working on hot rods.