Features of the .htaccess file

Modified on Sat, 11 May 2024 at 05:29 PM

The .htaccess (HyperText Access) file is intended for changing server settings for a specific directory and its subdirectories. This is an Apache server specific file and will not work with Nginx or Microsoft IIS.

WHY DO YOU NEED A .HTACCESS FILE?

Using the .htaccess file, you can make the following settings:

  • setting rules for processing URLs, as well as setting up redirection;

  • authorization settings;

  • restricting access from certain IP addresses and browsers;

  • customizing error pages;

  • encoding management;

  • transmission of additional headers;

  • PHP setup.

  • and etc.

WHERE IS THE .HTACCESS FILE LOCATED?

By default, in popular CMSs the .htaccess file is located in the root directory of the site. If necessary, it can be added to a subdirectory if it requires individual rules.

.HTACCESS FILE SETTINGS

CHANGING THE HOME PAGE

You can change the main page of a site using the DirectoryIndex directive. To do this, the file name of the main page is specified in .htaccess.

For example:

DirectoryIndex index.php index.html

Please note that you can list multiple files separated by a space; if the server does not find the first file, it will use the second one.

CHANGING THE ERROR PAGE

In the .htaccess file, you can replace standard error pages with your own.
The ErrorDocument directive will specify which page the web server should display when a specific error occurs.

ErrorDocument 403 /403.html ErrorDocument 404 /404.html ErrorDocument 500 /500.html

In this example, we specified which site files to use to display 403, 403 and 500 errors.

SETTING THE CODING

To set the charset via .htaccess, you can use the AddDefaultCharset directive.

AddDefaultCharset UTF-8

In this case, the site will be set to serve pages in UTF-8 encoding. The encoding can also be changed using php_value for PHP.

php_value default_charset utf-8

CONFIGURING FORWARDING IN .HTACCESS

You can configure redirection using Redirect and mod_rewrite rules.

CHANGING PHP SETTINGS

Using php_value in the .htaccess file you can change PHP settings, for example:

  • amount of memory for script execution;

  • script execution time;

  • size of the downloaded file.

CACHE SETTINGS IN .HTACCESS

Correctly configured caching in .htaccess will reduce the load on the server and speed up the delivery of site pages for users. Let's look at several ways to configure caching in .htaccess.

<IfModule mod_expires.c>    # Включаем кэширование    ExpiresActive On    # Устанавливаем время жизни кэша для статических файлов    ExpiresByType image/jpeg "access plus 1 year"    ExpiresByType image/png "access plus 1 year"    ExpiresByType image/gif "access plus 1 year"    ExpiresByType image/x-icon "access plus 1 year"    ExpiresByType text/css "access plus 1 month"    ExpiresByType text/javascript "access plus 1 month"    ExpiresByType application/javascript "access plus 1 month" </IfModule>

This code includes the mod_expires module, which allows you to set the cache lifetime for static files (images, styles, and scripts). In the example, we set the cache lifetime to 1 year for images and 1 month for styles and scripts.

If the server does not have the mod_expires module, then you can use mod_headers. Create a .htaccess file in the directory with images and add the following rules to it.

 # Включаем кэширование <IfModule mod_headers.c>    # Устанавливаем время жизни кэша на 1 день    Header set Cache-Control "max-age=86400, public" </IfModule>

In this example, we set the caching of all files in a directory to 86400 seconds (24 hours).

Please note that on the shared hosting side, caching of static files is enabled by default according to the recommendations of search engines.

PROTECTING THE DIRECTORY WITH A PASSWORD

The .htaccess file can be used to password protect a directory.

# Указываем тип авторизации AuthType Basic # Указываем путь к файлу для хранения списка пользователей AuthUserFile /var/www/.htpasswd # Указываем, что авторизированный пользователь будет иметь доступ Require valid-user

To create a file with user data, you can use the htpasswd utility, which is included in Apache. For example, to create a .htpasswd file with the user admin and password password in the /var/www directory, you can use the following command:

htpasswd -c /var/www/.htpasswd admin

When you run this command, you will be prompted to enter a password for the admin user.

PROHIBITION OF ACCESS BY IP ADDRESS

If necessary, in .htaccess you can use the Deny from directive to block access to certain IP addresses.

# Ограничение доступа с IP-адреса 127.0.0.1 Deny from 127.0.0.1 # Ограничение доступа для подсети 127.0.0.1/24 Deny from 127.0.0.1/24 # Ограничение доступа для всех IP-адресов Deny from all

ACCESS RESTRICTION BY USER AGENT IN .HTACCESS

You can protect your site from robots and bots using the .htaccess file. To do this, you need to use browser blocking (User Agent).

RewriteEngine On RewriteCond %{HTTP_USER_AGENT} (bot|crawl|spider) [NC] RewriteRule .* - [F]

This code blocks any request that contains the words bot, crawl or spider in the HTTP_USER_AGENT header (usually the name of the browser or bot/robot).

And here, we redirect all users using the Internet Explorer browser to the /eol.html page:

RewriteEngine on RewriteCond %{HTTP_USER_AGENT} MSIE RewriteCond %{REQUEST_URI} !^/eol.html$ RewriteRule ^(.*)$ /eol.html [R=301,L]

CONTROLLING VIEWING FILES IN A CATALOG

If there is no index.php or index.html file in the directory, you can use the rules in the .htaccess file to configure viewing of files and directories; the Options directive is responsible for this.

For example, to prevent viewing the contents of a directory, you can use the following rule:

Options -Indexes

Allow viewing directory contents:

Options +Indexes

LIMITING ACCESS TO FILES BY THEIR EXTENSION

In .htaccess you can deny access to files with a specific extension. The <FilesMatch> directive is used for this.

For example, let's deny access to files with the .php extension:

<FilesMatch "\.php$">  Order Allow,Deny  Deny from all </FilesMatch>

Similarly, you can allow access only to files with a specific extension:

<FilesMatch "\.(html|txt)$">  Order Allow,Deny  Allow from all </FilesMatch>

This rule only allows access to .html and .txt files.

Also note that the rule may not work for static files on shared hosting, since they are served by the Nginx web server, which does not take into account the rules specified in .htaccess.

COMMON ERRORS

Incorrectly specified rules in .htaccess can lead to various errors:

  • 403 Forbidden: occurs when a rule is set in .htaccess to deny access to a directory or file.

  • 404 Not Found: An error occurs when the requested address is not found. This can happen if .htaccess is set to redirect to a non-existent page or directory, or if the mod_rewrite rules are configured incorrectly.

  • 500 Internal Server Error: may appear if there is a syntax error in the .htaccess file, the path to the file or directory is incorrect, the rules are incorrect, or when using Apache modules that are not installed.

  • Infinite Loop Redirect: appears when the redirect rule in the .htaccess file leads to an infinite loop between pages.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article