10 .htaccess tricks that everyone should know.

With the help of the configuration file .htaccess, webmasters using NCSA-compatible web servers like Apache HTTP Server are able to set up directory-related rules. This allows webmasters to control which users have access to particular files. Setting up automatic redirects is also a typical example of one of the many .htaccess hacks.

So what is a .htaccess file?

.htaccess concerns text-based files that allow authorized users to influence directory-specific matters related to NCSA-compatible web servers. This technology was developed in the nineties by the then-leading web server, NCSA HTTPD. The main application of .htaccess today, however, is most commonly associated with the wide-spread Apache HTTP server. This server functions by controlling one or more central configuration files, commonly named “.httpd.conf”. These high-ranking configuration files are normally saved in the program directory of the web server itself and are defined by the server administrator. With the help of .htaccess tricks, this file further determines whether a user is allowed to receive an authorization that enables server configuration. In the case that such rights are granted, the user can then create and edit .htaccess files for every desired directory. This access also allows those with the respective rights to overwrite configuration parts on different directory levels.

Whenever a page is accessed, web servers recursively scan all high-ranking directories (.htaccess of a subdirectory overwrites a higher-ranking one) without creating a cache. Server settings that are performed with a .htaccess file are valid the moment that same file is stored in its proper directory. No server reboot is required. Notation at this juncture needs to be 100 percent accurate. An improperly entered .htaccess file can, under some circumstances, prevent site access on the entire server. When correctly carried out, .htaccess tricks offer some helpful features for managing web servers. These .htaccess hacks can be quickly implemented and are easy to embed into existing system structures.

How .htaccess files work

Given that .htaccess files are completely composed of text, they can be drafted and edited in any conventional text editor. Depending on available access to web servers, there are different ways to approach creating such files. Telnet or SSH access allows you to compile and edit .htaccess files directly on the server. Once the FTP access is available, the file has to be locally created and uploaded. As is typically the case with directory-specific files on Unix systems, this file also needs to begin with a dot. Such notation tells the operating system that the file is “hidden”, which can create the impression that the uploaded .htaccess file is missing when a graphic FTP client is involved.

The aforementioned point can also be a source of problems when locally creating a .htaccess file; this, however, is easily fixed. In order to prevent the editor from including the typical .txt file ending, select under the file type “All files” when saving. Once the .htaccess file has been mounted with the proper command, it simply needs to be transported to the desired directory. The file is immediately valid; this also counts for sub directories.

Configuring servers with .htaccess hacks

.htaccess files allow authorized users to quickly and easily influence the configuration of a web server. HTTP authentication makes it possible to protect entire directories from unauthorized access. Error pages or automatic transfers can also be set up with this process. There is a wide range of different .htaccess tips and tricks, and we have compiled 10 of the most useful ones for you below:

1. Alternative error pages

Default web servers display standard HTML files or hard-coded messages if an error occurs when a page is accessed. Such error reports are neither particularly helpful nor aesthetically pleasing. .htaccess enables users to feed in pages or messages that refer users to alternative content. Here are the statements used to integrate custom error reports:

#individual error reports at local storage 
locatioErrorDocument 404/directorypath/404.html

When error pages are located on an external URL or above the root directory of a website, it is possible to enter the entire URL into the .htaccess. The .htaccess file must be located in the root directory in the former case, however. 

#individual error report external storage location
ErrorDocument 404 www.domain.tld/directorypath/404.html 

2. Forwarding

Forwarding and redirects comprise some of the main uses of .htaccess files. Requests can be forwarded to another domain or individual file of a website, or can be redirected within a given site. Once saved in the root directory, the following code ensures that requests headed for the original server domain are rerouted to the new one:

#single forwarding
Redirect / http://www.new-domain.tld/

Using the same method, individual files can also be transferred within a website in the case that a site’s name is changed:

#forwarding individual documents
Redirect /old-page.html new-page.html

3. Restricted areas

Those wishing to forego the need of composing extensive log-in scripts with PHP, yet still require a protected directory or file on their server can use .htaccess tricks to set up restricted areas. This type of password protection requires a second file called “.htpasswd”. Relevant passwords are stored here, and may only be entered into Unix systems when encrypted. To this end there are many different .htpasswd generators available online. Protected directories can be set up by executing the following commands:

# basic password protection with .htaccess
AuthType Basic
AuthName "restricted area"
AuthUserFile /<absolute path to password file>/.htpasswd
AuthPGAuthoritative Off
require user User1 User2 User3

The .htpasswd is then created with the users, including their encrypted passwords.

# .htpasswd file for usernames and passwords
User1:duCmo1zxkKx6Y
User2:mou3IYjSLpGWI
User3:HGKS9XzDXXAXQ

While the .htpasswd files should ideally be placed in the root directory, the .htaccess needs to be in the directory that is to be protected.

4. Increasing PHP memory limits

PHP applications are constrained by a defined memory limit. This limit determines the maximum amount of working memory that PHP scripts are allowed to cumulatively take up. The following command in the .htaccess increases this limit as necessary.

# PHP Memory Limit
php_value memory_limit 128M

The value “128M” stands for the limit of 128 megabytes in this case. Depending on memory and server requirements, other limits can also be established.

5. Changing the time zone of a server

If the server is running in the wrong time zone, the following entry allows the proper adaption to take place in the .htaccess:

# set time zone
SetEnv TZ US America/Chicago

6. Block IP addresses

It’s possible to prevent certain IP addresses or ranges from accessing websites. The right entry can suspend all IP addresses and grant access only to certain addresses. Doing this can make websites available exclusively for the employees of proprietary intranets, for example. The following command is a summary of some of the possible access restrictions:

# File for adjusting IP ranges
Order deny,allow
Deny from .aol.com
Deny from 192.168
Allow from 192.168.220.102

The entry “Order” establishes the interpretation sequence of the registered entries; these can be entered in any order. The ensuing entries communicate to the server that all users with .aol.com and numeric IP addresses in the range of 192.168 are barred from using the site. An exception is made with the IP 192.168.220.102.

7. Redirecting a web presence from HTTP to HTTPS

Those using SSL certificates for their domain have the possibility of redirecting the domain to the encrypted HTTPS with the following command:

# activate HTTPS
RewriteEngine On
RewriteCond %{Server_Port} !=443
RewriteRule ^(.*)$ http://yourdomain.tld/$1 [R=301, L]

8. Activating file access through the browser

The following command enables the directory content to be shown in browsers and to be downloaded by users:

# show directory content
Options +Indexes 

9. Prohibiting pictures from being hotlinked

Hotlinking allows a third person to link media to their website (especially pictures) that are saved on a different host. Doing this increases the data volume for the actual owner. The following command allows users to prohibit certain file types on their own website form being linked:

# prohibit hotlinking
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://your-webhosting-domain/.*$ [NC] [OR]
RewriteCond %{HTTP_REFERER} !^http://www.your-webhosting-domain/.*$ [NC] [OR]
RewriteRule .*\.(gif|GIF|jpg|JPG|bmp|BMP|wav|mp3|wmv|avi|mpeg)$ - [F] 

10. Specify charset information for documents

Without a proper charset, incorporating different accents or other characters is not possible. This can be particularly frustrating for those wishing to work in languages other than English. A .htaccess file is able to determine precisely which character coding should be employed for particular types of documents. This command makes it possible to encode all documents with UTF-8:

#specify character coding
AddDefaultCharset utf-8 

Use the following commands in case only specific documents are to be coded:

#specify character coding for certain files
AddDefaultCharset utf-8 .css .htm .html .xhtml .php 

.htaccess tricks: practical and easy to use

The aforementioned tips and tricks are only but a small preview of the wide range of functions that .htaccess files can be applied to when configuring servers. The server follows all the commands immediately, and no restart is necessary