Let’s begin from a far distance with the goal that the novices can see how the file described in the article works. To work the website on the Internet, you need not just a PC and access to the network, yet additionally, extraordinary programming introduced on it, which gives access to information utilizing the HTTP and HTTPS conventions. This product is the web server. There are different sorts of web servers, however, the most widely recognized is Apache. It is based on the open-source code, free, is continually being improved and enhanced, compatible with many scripts, and works on almost all platforms, including Windows, Linux, Netware 5.x.

Apache is arranged by means of design documents that are put away in content organization. With their assistance, you can set explicit standards of activity of the web server. The principle design record is called httpd.conf or apache.conf (contingent upon the OS conveyance). Much of the time, all server setups can be determined here, and essentially this technique is best in light of the fact that:

reduces the response time of the web server when mentioned (so every time the web server is gotten to, Apache won't peruse all catalogues for .htaccess); a few orders, for instance, mod_rewrite module orders, in numerous regards, work better from the principle design record.

Be that as it may, not all clients of the server may approach this document (for instance, on account of shared facilitating), so the rest is offered an extra web server arrangement record — .htaccess (with a dab toward the start of the name).

Table of contents


  1. What does .htaccess stand for
  2. How to create a .htaccess file
  3. .htaccess syntax
  4. .htaccess opportunities
  5. Access control
  6. Working with web-server errors
  7. Adjusting redirect 301 in htaccess
  8. mod rewrite redirecting module
  9. Defining encoding
  10. Other opportunities
  11. If .htaccess does not work
  12. A few more several tips on working with .htaccess
  13. Useful links

What is .htaccess and what is it for?


The file (or files) .htaccess will set the rules for the web server only in the directory where it is located and its child directories, without global changes in the operation of the entire server. The ability to use .htaccess is prescribed by a directive (i.e., a command) — AllowOverride — in the main configuration file httpd.conf, the name of which directly indicates that the settings inside .htaccess take priority over the settings in httpd.conf (unless otherwise limited by all same directive AllowOverride). With this directive, you can allow everything, and you can — just some actions. Detailed instructions for its use can be found on the Apache website.

With it, each time a web server is accessed, Apache will scan all directories for .htaccess. Changes in the file are valid immediately after saving — the restart of the entire web server is not needed (unlike changes in httpd.conf).

The name of the .htaccess file is common, but not at all mandatory. You can set a different name in httpd.conf using the AccessFileName directive, for example:

AccessFileName .config

How to create a .htaccess file


As already mentioned, the configuration files have a text format, and you can also create .htaccess using a text editor (for example, Notepad or NotePad ++ in Windows).

The file name is .htaccess (with a dot at the beginning);

type — “All files”;

word wrap;

ASCII mode (when uploading .htaccess to a hosting using an FTP protocol).

Apache is a case-sensitive web server, so it is important to write the name in small letters: .HTaccess and .htaccess are different files.

Mac OS files starting with a dot are invisible. Therefore, you can call it differently and after, transferring via FTP to the hosting, rename it. Usually they place the file in the root directory of the web server (/ public_html) or in the root directory of the site (/public_html/site.com/).

.htaccess syntax


The .htaccess syntax is similar to the httpd syntax. For each directive, a separate line is assumed. For your own convenience, you can add comments to the file using the # sign, and the value after # will be ignored by the web server. This trick can be used to disable any directive. It does not need to be removed completely from the file — just comment it out.

The possibilities of the configuration file are enormous. Below are the basic settings in .htaccess.

.htaccess opportunities


Access control


Web access ban:

Order Deny, Allow
Deny from all

Web access ban, except for IP:

order deny, allow
deny from all
allow from xxx.xxx.xxx.xxx

Web access ban for IP:

Order allow, deny
Allow from all
Deny from xxx.xxx.xxx.xxx

File access ban:

<Files private.html >
Order allow, deny
Deny from all

Directory security with the password:

AuthType Basic     
AuthName "Directory Name"
AuthUserFile /home/cpanel_user/.htpasswds/public_html/smth/passwd
require valid-user

# where AuthName "Directory Name is the secured directory name, аnd 
# /home/cpanel_user/.htpasswds/public_html/smth/passwd is the file location with the password.

Working with the web-server errors


Sometimes, instead of the expected page, a visitor may encounter a web server response in the form of an error with a concise, but not always clear for a simple user, explanation of the reason. A complete list of status codes can be found on Wikipedia. For the most common (for example, 404 or 500 errors), it is desirable to create your own page that looks better and presents the exit route to the visitor. It is set as follows:

ErrorDocument 404 yourdomain.com/error/404.html
# where yourdomain.com/error/404.html is the path to the created page.

Adjusting the redirect 301 in htaccess


To create a permanent redirect, the directive 301 redirect is used, which transfers the entire weight of the page to a new url (therefore, it is preferable to a 302 redirect for SEO purposes).

Redirecting the entire site to a new domain:

Redirect 301 / http://www.newdomain.com/

Redirect page to new:

Redirect 301 /page1.html http://mydomain.com/page2.html

Mod rewrite redirect module


The mod_rewrite module is an indispensable mechanism for changing URLs “on the fly”. Its utility, and at the same time, the difficulty lies in the fact that you can use a myriad of rules that include even more variables.

For the module to work, first of all we need directives

RewriteEngine On (includes the conversion engine)

Options FollowSymLinks (mod_rewrite operation condition).

If the server administrator has disabled this option for the user directory, then the conversion mechanism cannot be used. This restriction is imposed on virtual hosting servers for security purposes.

For further acquaintance with the module we recommend to refer to the source.

RewriteRule


One of the most functional directives of the mod_rewrite module is the RewriteRule. To specify the condition under which the rule will work, the RewriteCond directive is used. It (one or more) must be prescribed before the RewriteRule.

Redirect page to new domain:

RewriteRule ^ page1 \ .html $ http://newdomain.com/ [R = 301]

Redirecting a site from a domain without www to a domain from www:

RewriteEngine On
RewriteCond% {HTTP_HOST}! ^ Www \ .. * [NC]
RewriteRule ^ (. *) Http: //www.% {HTTP_HOST} / $ 1 [R = 301]

And vice versa:

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

HTTPS redirection (you must first install an HTTPS certificate):

RewriteEngine On
RewriteCond% {https}! On
RewriteRule (. *) Https: //% {HTTP_HOST}% {REQUEST_URI} [R = 301, L]

These lines must be placed at the very top of .htaccess.

Defining the encoding


The symbol table in which to open the site is determined by the browser. However, you can set the default encoding:

AddDefaultCharset UTF-8

Such a change applies within .htaccess and to all pages of the site. You can set the encoding for a specific type of file, for example windows-1251 for html:

AddType "application / x-httpd-php3; charset = windows-1251" .html

Often the page itself carries in itself (namely in the title) information about the encoding used. It is necessary to check that the specified encoding in the document and in the configuration file matches. The utf-8 given here is almost always required when working with popular cms, since they are designed for a wide range of users around the world. By the way, by default, the same encoding is configured on our shared hosting servers.

Other opportunities


— Determine the site index file:

By default, the index page is considered index.html. With the help of the following directive, you can specify another file name that comes off first when accessing the directory:

DirectoryIndex index.php

— A useful directive is FilesMatch, which specifies the limits of the rule by file name using regular expressions. With its help, for example, you can deny access to certain files:

<FilesMatch
"\. (htaccess | htpasswd | ini | phps | fla | psd | log | sh) $">
Order Allow, Deny
Deny from all
</ FilesMatch>

There are some directives that are not supported on our shared hosting servers, but you can allow them on your VPS, for example.

The reason is that the web server running as suPHP does not support php_flag and php_value. Therefore, we suggest using cPanel (the subsection “Choosing a PHP Version” subsection is extremely useful, to work with error_log — “Error Log”) or to create a local php.ini file for this purpose. We did bring a couple of directives below:

— In order to avoid a web server freeze when processing incorrectly written scripts, there is max_execution_time. With its help, the time in seconds allocated for processing the PHP script is indicated. You can increase the timeout of the web server when executing the script:

php_value max_execution_time 60

— Determine the maximum upload file size:

php_value upload_max_filesize 128M (here, instead of 128, put the desired value)

— Print PHP errors into a separate file:

php_flag log_errors on
php_value error_log /home/path/to/public_html/domain/PHP_errors.log
# PHP_errors.log is the name of the file, and
# / home / path / to / public_html / domain - the path to it).

P.S. On a shared hosting, it is difficult to accurately determine which directives will work in .htaccess, because many of those that lead to a web server configuration change are prohibited for obvious reasons — these changes will affect all users on the media.

If .htaccess does not work


You can check the file operation by writing simple directives that, with the correct syntax and correct httpd settings (as described at the beginning of the article) should work:

— for example, by denying access to the site from the outside using a directive

Order deny, allow
Deny from all

— or writing to the file a set of meaningless characters that are not directives. If the web server interacts with htaccess, then, of course, it will not be able to read them and give 500 error.

If the problem really exists, you must first look for the cause in the main configuration file:

— make sure that the server allows the use of the .htaccess file: there is an AllowOverride All entry (and it is not commented out using #);

— verify that a VirtualHost entry has been created for the domain. As an example:

<VirtualHost *: 80>
DocumentRoot / www / example1
ServerName www.example.com
# Other directives
</ Virtualhost>

— the name of the additional configuration file is indicated as you need. If it is .htaccess, then:

AccessFileName .htaccess

— the hostname of the server is present (specified when creating URL redirects) as the IP address of the server or domain:

ServerName www.example.com

If the reason is not in httpd, you need to check .htaccess itself for syntax errors. You can use online services (for example, www.htaccesscheck.com, htaccess.madewithlove.be), or — the original source, where there is a complete list of directives, along with the syntax.

A few more several tips on working with .htaccess


It is highly desirable to make a backup copy of the file before any editing, so that at the worst outcome you can “roll back” the changes back.

We recommend making changes step by step, using a minimum of directives — and in case of failure it will be easier to calculate which rule caused the error.

Although the changes take effect immediately, the browser’s cache hasn’t been canceled — to check the work of the site after editing .htaccess, use it to clean it regularly or load the page to bypass the cache — via the key combination Ctrl + F5 (in Safari: Ctrl + R, on Mac OS: Cmd + R).

The most common web server error when working with .htaccess is 500, and either it indicates a problem in the syntax (typo in a directive, for example), or this type of directive is not allowed in the main configuration file.

Useful links


Inspiration for working with .htaccess:
httpd.apache.org/docs/2.2/howto/htaccess.html
Many instructions for working with .htacess:
htaccess.net.ru
Blogging platform for programmers:
writeabout.tech
Simple directive generator for .htaccess:
htaccess.ru/generator

In case .htaccess file is not enough for you to make changes in the web server configuration file, you can rent an allocated server in Europe or the USA. These servers can provide you with an opportunity to make changes in the Apache’s settings.

Комментарии (0)