You get a bonus - 1 coin for daily activity. Now you have 1 coin

.htaccess - Usage and Syntax

Practice



In the world of web development, the .htaccess file is often used when hosting sites managed by an Apache server. This is a very useful file, allowing you to define undefined options, or override options defined in httpd.conf or apache.conf, for a specific site or a directory of that site.

The file applies to the current directory (where it is located) and to all directories "below" it, i.e. all child directories, unless they have their own .htaccess file defined.

In this article I will lay out a number of the most commonly used capabilities of this file. Of course, not everything is described here - you can learn a lot more from the vastness of the internet - but the most frequently encountered questions are covered.


Writing rules

Directives in the file are specified one per line.

All paths start from the root of the site (not from the root of the server's file system!)

For example, if the needed file on the server is located at /var/www/mysite.ru/mydir/file.html, then the correct path would be /mydir/file.html

If a url is being specified, it must always be specified together with the protocol.

For example, if there's a redirect to the site www.mysite.ru, you need to specify http://www.mysite.ru


Comments - everything located after the # character

Environment variables can be used in expressions. A list of the most commonly used ones is below.

Finally, when you make changes to the file - they take effect immediately. Nothing needs to be restarted.


Environment variables

Although not often, environment variables can still be used in the .htaccess file. Some of them are given below (thanks to the site htaccess.net.ru):
  • QUERY_STRING (request parameters)
  • REMOTE_ADDR (visitor's IP address)
  • REMOTE_HOST (visitor's host name)
  • REMOTE_USER (username, if the user has been authenticated)
  • REMOTE_METHOD (browser method - GET or POST)
  • PATH_INFO (path to the web page file)
  • HTTP_USER_AGENT (contents of the user-agent header - browser type)
  • HTTP_REFERER (contents of the referer header)
  • HTTP_COOKIE (contents of the cookie header)
  • HTTP_HOST (host name of the website)
  • TIME_YEAR (year, month, etc.)
  • TIME_MONTH
  • TIME_DAY
  • TIME_HOUR
  • TIME_MIN
  • TIME_SEC
  • TIME_WDAY
  • REQUEST_URI (requested URL)
  • REQUEST_FILENAME (requested file)
  • THE_REQUEST (the request in full)


Regular expressions in .htaccess

Regular expressions can be used in this file. Their syntax is given below. Thanks to the site htaccess.net.ru

A regular expression can use any printable character and space, but some characters have a special meaning:

  • Parentheses () are used to highlight groups of characters.
  • The ^ character denotes the beginning of a line.
  • The $ character denotes the end of a line.
  • The . character denotes any character.
  • The | character denotes an alternative. For example, the expressions "A|B" and "(ABC|DEF)" mean "A or B" and "ABC or DEF" respectively.
  • The ? character is placed after a character (or group of characters) that may or may not be present. For example, the expression "jpe?g" matches both the string "jpg" and the string "jpeg". Example of an expression with a group of characters: "super-(puper-)?site".
  • The * character is placed after a character (or group of characters) that may be absent or present an unlimited number of times in a row. For example, the expression "jpe*g" matches the strings "jpg", "jpeg", and "jpeeeeeeg".
  • The + character works similarly to the * character, with the only difference that the preceding character must be present at least once. For example, the expression "jpe+g" matches the strings "jpeg" and "jpeeeeg", but not "jpg".
  • Square brackets [ ] are used to list allowed characters. For example, the expression "[abc]" is equivalent to the expression "a|b|c", but the version with square brackets is usually more optimal in terms of performance. Ranges can be used inside the brackets: for example, the expression "[0-9]" is equivalent to the expression "[0123456789]". If the characters inside square brackets start with the ^ character, this means any character except those listed in the brackets. For example, the expression "[^0-9]+" means a string of any characters except digits.
  • The \ character is placed before special characters if they are needed in their original form. For example, the expression "jpe\+g" matches only the single string "jpe+g".
  • Everything located to the right of # is considered a comment.


How to enable it

On Linux (LAMP), using the .htaccess file is usually already allowed in the Apache configuration. On FreeBSD, you may need to specifically enable the use of this file with the AllowOverride directive in the global configuration or in the configuration of a specific site.

AllowOverride All


Denying read access to all files in a directory

deny from all


Access from a specific IP address

oder deny,allow
deny from all
allow from 192.168.0.1
allow from 192.168.0.2

where instead of 192.168.0.1, 192.168.0.2 you specify the IP addresses from which users are allowed to access the site. Otherwise - error 403.


Denying access from specific IP addresses

order allow,deny
allow from all
deny from 192.168.0.1
deny from 192.168.0.2

Instead of the specified IPs, you need to specify those for which access is closed.


Denying access to files by mask

<Files "\.(ext1 | ext2 | ext3)$">
order allow,deny
deny from all
</Files>

Instead of ext1, ext2, ext3... insert your own extensions. The allow/deny rules are defined the same way as for the directory as a whole.

As a special case - you can set access for one specific file (though, given the inheritance of .htaccess permissions - this access or restriction will apply to all subdirectories - i.e. to all files in this directory and all directories below it):

<Files myfile.html>
order allow,deny
deny from all
</Files>


Password-protecting a directory

Often used when creating websites where access (or access to part of them) is not allowed to everyone. When trying to open this url, the web browser will prompt the user for a login and password.

AuthName "Введите пароль для доступа"
AuthType Basic
AuthUserFile /var/www/mysite.ru/.htpasswd
require valid-user

ATTENTION! Note that here the path to the .htpasswd file is specified from the root of the server's file system, not the site!

To use this method you need to have a .htpasswd file. How to create and use it is described on this same site in the web section. Here's an example of creating this file:

# htpasswd -c /var/www/mysite.ru/.htpasswd username password

If the -c flag is not specified, the htpasswd utility will not create the file anew, but will add the user username to the ones that already exist.

Keep in mind that with this authentication method, the login and password are transmitted in plain text, so it is recommended to use the HTTPS/SSL protocol.

As a special case, this construct can be used inside a <Files> </Files> block to password-protect only certain files.


Complex password protection


Suppose there's a site structure:

/mysite.ru/A
/mysite.ru/A/B1
/mysite.ru/A/B2


We need to make it so that authentication is required for all users accessing directory A, but at the same time some users have access to directory B1, and other users have access to directory B2.

We will need .htaccess files in each directory.

.htaccess for directory A:

AuthName "Введите пароль"
AuthType Basic
AuthUserFile /var/www/mysite.ru/A/.htpasswd
<Files *.*>
require valid-user
</Files>

.htaccess for directory B1:

AuthName "Введите пароль"
AuthType Basic
AuthUserFile /var/www/mysite.ru/A/.htpasswd
<Files *.*>
require user username1 username2 username3
</Files>

.htaccess for directory B2:

AuthName "Введите пароль"
AuthType Basic
AuthUserFile /var/www/mysite.ru/A/.htpasswd
<Files *.*>
require user username1 username4 username5
</Files>

Instead of usernameX, substitute the names of the users who have access to the corresponding directories.


Redirecting to another site

Method 1:

Redirect / http://www.anothersite.ru

If the redirect is permanent (i.e. forever - which is very useful for search engines), the syntax will be as follows:

Redirect permanent / http://www.anothersite.ru

If you use the word temp instead of permanent - the redirect will, conversely, be temporary.

Another example of a redirect - from a specific directory within the site:

Redirect /dir2 http://www.anothersite.ru/dir2


Method 2:

Instead of the Redirect directive, we use the RedirectMatch directive. The difference is that instead of specifying the address to redirect from, a regular expression is specified.

RedirectMatch (.*)\.gif$ http://mysite.ru/$1.png

Redirects all requests for .gif to files with the same name but with the .png extension, located at mysite.ru/

Another example:

RedirectMatch (.*\.jpg)$ http://mysite/$1


Method 3:

Recommended for moving a domain for faster reindexing by search engines, using RewriteEngine (if it is allowed on the hosting and its module is loaded).

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.old_site\.ru$ [NC]
RewriteRule ^(.*)$ http://new_site.ru/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^old_site\.ru$ [NC]
RewriteRule ^(.*)$ http://new_site.ru/$1 [L,R=301]


Showing different pages depending on the user's IP address

SetEnvIf REMOTE_ADDR 192.168.0.1 REDIR="redir"
RewriteCond %{REDIR} redir
RewriteRule ^/$ /another_page.html

Instead of 192.168.0.1, insert your own value.


Replacing the start page

DirectoryIndex another_file.php

Essentially, here we are overriding the DirectoryIndex directive specified in the httpd.conf or apache.conf file.


Replacing error pages

ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html

This way, when, for example, a 404 error occurs, the browser will not display its own page, but will try to load a styled page from the site.

Of course, you can specify further error codes as well - this is just an example.


Disabling the display of a file listing in directories without an index file

Options -Indexes

This way the user will not be able to display the contents of a directory that has no index file (and in a directory that has an index file - they cannot do this by default anyway).


Specifying the display encoding

You can tell the browser which encoding the files are transmitted in. This will reduce the likelihood of an error in automatic encoding detection, if the files are transmitted in one encoding but the browser, for some reason, starts displaying them in another.

AddDefaultCharset windows-1251


Specifying auto-conversion of the encoding of uploaded files

When files are uploaded to the site, they will be automatically converted to the specified encoding.

CharsetSourceEnc koi8-r


Adding MIME handlers

AddType "text/html" .myext
AddType "application/x-rar-compressed" .rar

This way we can add directives to our site that are not described in the global Apache config.


Blocking specific User-Agents (web browsers, bots, and robots)

Here's a snippet of the .htaccess file, in which several User-Agents (web browsers; bots, really) are blocked.

SetEnvIfNoCase User-Agent "^Titan" bad_bot
SetEnvIfNoCase User-Agent "^Wget" bad_bot
SetEnvIfNoCase User-Agent "^SiteSnagger" bad_bot
SetEnvIfNoCase User-Agent "^WebAuto" bad_bot
SetEnvIfNoCase User-Agent "^NetAnts" bad_bot
SetEnvIfNoCase User-Agent "^WebZip/4.0" bad_bot
SetEnvIfNoCase User-Agent "^httplib" bad_bot

<Limit get="" post="" head="">
Order Allow,Deny
Allow from all
Deny from env=bad_bot
</Limit>

The list of "bad" User-Agents here is very small and is given only as an example.


PHP settings

In addition to the httpd.conf and apache.conf variables, we may also find it useful to change the php settings values defined in php.ini. The .htaccess file also lets us do these nice things. For this, the php_value and php_flag directives are used.

The difference between php_value and php_flag: the first directive assigns a specific value to a setting:
php_value <config_setting> <value>
while the second enables or disables a boolean setting:
php_flag <config_setting> <on|off>

ATTENTION! You cannot use php_admin_flag and php_admin_value in the .htaccess file!

For example, the code

php_flag magic_quotes_gpc 0
php_flag magic_quotes_runtime 0

will disable automatic data escaping in PHP (will disable MagicQuotes), and the code

php_value memory_limit 64M


will override the value of the maximum amount of memory allocated for the site.

These values override the values defined in the php.ini file, or define them if they were not set by the hosting server administrator. There's no point listing the entire list of php settings here - you can find them in the php documentation for the version you need.


The Rewrite module

The Apache server includes the Rewrite module. Even though it is used in the .htaccess file, we will not describe it now, since it is a separate topic deserving of its own separate article.

Applies to: Apache 2.x



This is far from everything you can do with the .htaccess file. There are a lot of specific examples out there on the internet; here we've gathered the most commonly needed examples.

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)