Logbook. Useful hacks and snippets for .htaccess

Allow access from a specific ip: order allow deny
deny from all
allow from<ваш ip>In this case, <ваш ip> indicates a specific address.
For example: order allow deny
deny from all
allow from 192.126.12.199

Deny access from a specific ip: order allow deny
deny from all
deny from<ваш ip>Usage <ваш ip> similar for the example above.

Depending on the order in which the directives are specified, the logic of the server’s operation changes. If Deny, Allow, then access is denied from all IPs except those specified, if Allow, Deny, access is allowed from all IPs except those specified. Next should be description sections for access and prohibition. Keyword all means from everyone IP

For example, we want to deny (block) access from IP 81.222.144.12 and 81.222.144.20 and allow everyone else we need to add to .htaccess the following code:

Order Allow, Deny
Allow from all
Deny from 81.222.144.12, 81.222.144.20

For the reverse situation when we want to deny access from everyone IP in addition to 81.222.144.12 and 81.222.144.20 we need to add to .htaccess the following code:

Order Deny,Allow
Deny from all
Allow from 81.222.144.12, 81.222.144.20

To allow only specific hosts or groups of hosts to access the server, the host can be specified in any of the following formats:

  • for a domain name (or part of it): Allow from apache.org
    Allow from .net example.edu
  • for ip address: Allow from 10.1.2.3
    Allow from 192.168.1.104 192.168.1.205
  • for part of the ip address:
    Allow from 10.1
    Allow from 10 172.20 192.168.2
  • for network/mask pair: Allow from 10.1.0.0/255.255.0.0
  • for network/nnn CIDR specifications:
    Allow from 10.1.0.0/16

Ban a group of files by mask:
order allow,deny
deny from all
Determines access to a file by its extension.
For example, denying access to files with "inc" extensions for web visitors:

order allow,deny
deny from all

In this example, the Apache web server itself can access files with such extensions.

Ban on a specific file:
You can block a specific file by its name and extension.
order allow,deny
deny from all
In this example, access to the config.inc.php file is prohibited.

Directory password: AuthName "Private zone"
AuthType Basic
require valid-user
The AuthName value will be displayed to the visitor and can be used to clarify the authorization request. The AuthUserFile value indicates the location where the file with passwords for accessing this directory is stored. This file is created by a special utility htpasswd.exe.

For example, in a directory that is protected with a password, we create the following .htaccess: AuthName "For Registered Users Only"
AuthType Basic
AuthUserFile /pub/site.ru/.htpasswd
require valid-user
In this example, when a visitor requests a directory, he will read the phrase “For Registered Users Only”; the file with access passwords should be in the /pub/site.ru/ directory and called.htapasswd. The directory is specified from the server root; if you specify the directory incorrectly, Apache will not be able to read the .htpasswd file and no one will have access to this directory.

Password for only 1 file:Tue Feb 09 2010 15:44:59 GMT+0300
Similar to passwording a whole directory, you can put a password on only 1 file.
An example of setting a password for the private.zip file:
AuthName "Users zone"
AuthType Basic
AuthUserFile /pub/home/your_login/.htpasswd

Password for a group of files:
Likewise, using , you can set passwords based on file masks.
An example of setting a password for access to all files with the "sql" extension:

AuthName "Users zone"
AuthType Basic
AuthUserFile /pub/home/your_login/.htpasswd

If you install WordPress on your own hosting, then you will have the opportunity to manage the root directory. Today I want to tell you about the .htaccess file, which is important for several reasons. With it, you can set various security settings, add redirect conditions, block bots, protect your own blog from spammers, and much more. However, many WordPress users still don't know anything about .htaccess and how to create one specifically for WP. Today I'll walk you through the many aspects of this file and in the future I'll share with you handy and effective code snippets designed to improve the security of your blog.

What is a .htaccess file?

Htaccess is not only for WordPress, but for any website hosted on an Apache web server. When installing WordPress, this file is created by default in most cases, but remains hidden in the root directory of your site. There are times when this file is missing altogether and then you need to manually create the .htaccess file. We can use a regular text editor to update or delete the contents of this file. In WordPress, the standard content of this file looks like this:

# BEGIN WordPress RewriteRule ^index\.php$ – [L] RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule . /index.php [L] # END WordPress

If you have a question about how to edit deep links in WordPress and give them the format /%postname?, and you even found some code to paste into the .htaccess file (but can't find the file in your system console or root directory) then today I will show you how to solve this problem.

How to create a .htaccess file for WordPress?

In most WordPress installations, a .htaccess file is present by default in the root directory. If you are using the Filezilla FTP client, you can refer to the existing guide on how to edit the .htaccess file for help. All you need to do is click on the option to show hidden files. If the file we need is missing altogether, then you can simply create it using notepad (htaccess.txt), and then rename it to .htaccess. Make sure that the file name is exactly that and not .htaccess.txt. If you are using Windows, you can disable the option to hide file extensions. Once you rename the file, upload it to your WordPress root directory and edit it as per your requirements. If you have problems changing the file name, simply upload the htaccess.txt file to the server, and change the name on the server.

The standard security permissions for the .htaccess file are 644, but if you change direct links through the WP console, the system will be denied access to this file. You can change them to 777. But be sure to then return the value to 644, otherwise it may cause serious security holes in the site.

Many Apache server users use the htaccess configuration file to configure the site. On the one hand, this decision cannot be called wise and worthwhile, since an overly filled htaccess file can harm the speed of the server. But some options in this configuration document are difficult to configure without using an htaccess file, for example, restricting access to a file, directory, or site as a whole. In the article below, you will learn how to use this htaccess file feature and what it is for.

Who needs access denial and how to use it

It is worth considering that the htaccess file allows you not only to deny access to the entire site at once, but also to create white and black lists of users. That is, you can, for example, block access for some IPs. In the same way, you can remove the ban only for the IPs you select, thereby creating a white list of users. But why use this feature at all?

Sometimes circumstances are such that no one should be allowed near the site. For example, when some important technical work is being carried out on it. At this point, you can block access for every user except your IP. Then visitors will not be present on the resource when it is in an unstable state. In addition, using a blacklist of users, you can deny access to the site for the IP of unfriendly visitors who spam, flood, swear and call bad names about your portal.

This way, you can close your site from unwanted guests by creating something like a ban list. And the htaccess file with its irreplaceable directives will help you with all this.

How to deny access to a file, directory, website via htaccess

To control the level of access to a site, file or folder, you will need to use the Deny and Allow directives. The first directive is needed to deny access, and the second is needed to allow. A lot of these directives depend on where you place the htaccess file. If it is located in the root directory, then the ban or permission will apply to the entire site. If you download htaccess to a folder, then the Deny and Allow options will apply to the directory in which it is located, as well as to internal folders. This is exactly how access to certain directories and sections of the site is blocked.

The syntax of the deny and allow directives is extremely simple. The option should begin with the line Order Deny, Allow. It indicates the activation of the Deny and Allow functions. And in the following lines you must indicate specifically what access conditions you plan to set. So, to block access for everyone, you need to write only two lines:

Order Deny,Allow - opening a function.
Deny from all - specifying the rule.

The bottom line says: "Deny (deny) for (from) all (all)." In exactly the same way, you can write Allow instead of Deny to activate the opposite option. But since this option is enabled by default, there is no point in specifying it additionally in htaccess. Allow from is rather used to indicate exceptions, that is, to create a white list of users.

To open access to only some IPs, you need to first close the site or directory to everyone else. Here is an example of creating a whitelist for two IP addresses:

Order Deny,Allow
Deny from all
Allow from 136.68.81.3, 135.67.82.1 - write IP separated by commas.

By analogy with the written function, you can block only certain IP addresses. Only for this you will need to first register permission for everyone via Allow from all, and then specify via Deny from IP addresses, or the names of hosts for which access is strictly prohibited.

To restrict rights to a file by blocking access, you need to create a separate htaccess document and place it in the directory where the file is contained. The deny directive for a file looks much the same as the access restriction option for a site or directory. The only difference is that you need a special tag to restrict the file. In the opening tag you must indicate the name of the object to which access should be restricted. Here is an example of a ban for all users to the passvd.txt file:

File name tag
Order Deny,Allow - opening an option
Deny from all - directive rule
- closing tag

Now all you have to do is place htaccess in the directory that contains the passvd.txt file, and no one will be able to access it through the site. As practice shows, access to a file is usually not completely blocked, but exceptions are specified for trusted IP addresses. For example, you can specify a restriction for everyone except your IP, so that you can then download a file with passwords. Here is an example of such a restriction:


Order Deny,Allow
Deny from all
Allow from 144.66.55.2

If the directory contains not one file that you need to protect, but several, then you can write many directives for each individual object at once. But it's inconvenient. In addition, many options in htaccess load the server, so it is much more reasonable to activate another blocking - denying access by the type of files in the directory, and not by their name. You will need to use exactly the same directive construction, only instead of the file name you need to use the “|” symbol. indicate extensions that users will not be able to download from this folder. Here is an example of a ban tag for loading images of a certain format:


Directives

To ban other formats, you only need to change the names of the extensions in brackets. This is easy to do, as is specifying a white or black list of users. The construction itself in quotation marks always remains the same.

Please note that many users do not use a static IP, but a dynamic one, so specifying one address in the ban is stupid. It makes more sense to include a range of IP addresses in the ban. To do this, find the Whois service and determine the CIDR of the IP address, and then indicate it in the ban. Then, even if the address is temporarily changed, the user will not be able to log into the portal.

By typing the address into the browser bar, you receive files on your computer that the browser displays. The web server controls which files and how to show (send) them to you. There are two most popular servers: IIS and .

Like any program, a web server has certain settings. But, you, as an Apache user, may (and most likely will not, if we talk about shared hosting) have the rights to change the Apache configuration through its main files, the effect of which applies to all users of this server. But, you can change some configuration files, which only apply to your site. One of these files is .htaccess

This is a flexible configuration file for the Apache web server. "Flexible" means that as soon as you change something in this file, the changes immediately take effect. Using it you can override many directives from the file httpd.conf(this file is the main configuration file of the Apache server and its actions apply completely to all users of this copy of Apache). In cases where you do not have access to the Apache configuration file (the same virtual hosting), this file will help you.

This file is not accessible to the web user from the browser. If file. htaccess is located in the root directory of the server, its actions apply to the entire server, except for those folders where another file is located. htaccess(and in addition to all the folders “below” this folder with the second. htaccess).

The structure of your directories on the server is like this:

|-user | | | -user1 | | | -user2 | |-data | | | -data1 | | | -data2 |

Directories user1 And user2 will be nested in relation to the directory user. If we put it in a directory www file. htaccess, then its effect will automatically extend to directories user1 And user2.

To directory data put another file. htaccess, compared to what is in the directory user. For both the data1 and data2 directories, the .htaccess file located in data will operate.

The .htaccess file is one of those files that every website administrator should know and understand. At a basic level, it controls access to site folders. But there are many more tasks that htaccess can solve for you.

1. Controlling access to files and directories

Password protection is one aspect of the issue, but sometimes you need to completely block a user from accessing certain files or directories. Such tasks usually occur for system folders, for example, includes . The application must have access to them, and the user loses all privileges.

To solve the problem, add the following code to the .htaccess file and save it in the desired directory:

But such a move blocks access for everyone, including you. To ensure access, you need to specify your IP address. Here's the code:

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

xxx.xxx.xxx.xxx is your IP address. If you replace the last three digits with 0/12, for example, the range of IP addresses on one network will be indicated. But this approach can lead to problems, so it is better to specify the list of IP addresses separately.

If you need to block a specific file, including .htaccess itself, use the following code:

order allow, deny deny from all

Likewise, if you need to allow access from certain IP addresses, list them using allow from .

If you need to block access to certain types of files, use the following code:

Order Allow,Deny Deny from all

2. We prohibit viewing the directory

To prevent viewing the contents of a directory, use the following code:

Options All -Indexes

But if you need to allow browsing of the directory for some reason, use the following code:

Options All +Indexes

3. Speed ​​up downloads by compressing files

You can compress any files, not just images. For example, to compress HTML files, use the following code:

AddOutputFilterByType DEFLATE text/html

And for text compression:

AddOutputFilterByType DEFLATE text/plain

You can also compress JavaScript files or define multiple file types for archiving:

AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml

Alternatively, you can compress all HTML, JavaScript, CSS and other files using GZIP:

mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text\.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_ item_exclude mime ^ image\.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

4. Protecting the site from hotlinking

If you want to prevent images from being hotlinked from your site, add the following lines to your .htaccess file:

RewriteEngine on RewriteCond %(HTTP_REFERER) !^$ RewriteCond %(HTTP_REFERER) !^http(s)?://(www\.)?yourdomain.ru RewriteRule \.(jpg|jpeg|png|gif)$ -

Just replace yourdomain.ru with your domain name.

5. Blocking users redirected from a specific domain

If you do not welcome users of a certain domain, you can ban them from your site. For example, if your site is listed where traffic is not wanted from (for example, pornographic sites, neo-Nazi resources, etc.), then you can block it using a 403 page (deny access). Mod_rewrite needs to be enabled (usually it is enabled). Add the code:

RewriteEngine on RewriteCond %(HTTP_REFERER) bannedurl1.com RewriteCond %(HTTP_REFERER) bannedurl2.com RewriteRule .* - [F]

You need to replace bannedurl1.com and bannedurl2.com with domain names from your blacklist. The flag indicates that the domain name is not case sensitive, and the [F] flag determines the action - in our example, displaying a 403 page. If you need to ban several sites, use the flag for each domain, including the last one. To ban only one domain, you can only use the flag.

6. Blocking requests from certain agents

If you have logged activity from certain user agents (bots or spiders) that you don't like, you can add a few lines to your .htaccess file to prevent those agents from accessing your site:

RewriteEngine On RewriteBase / SetEnvIfNoCase Referer "^$" bad_user SetEnvIfNoCase User-Agent "^badbot1" bad_user SetEnvIfNoCase User-Agent "^badbot2" bad_user SetEnvIfNoCase User-Agent "^badbot3" bad_user Deny from env=bad_user

7. File caching

Another method to make your site load faster is by caching files. Here's what you need to add to your .htaccess file to enable caching:

Header set Cache-Control "max-age=2592000"

You can add file types (or remove some of them) to the list in the example. You can also use max-age to specify the time in seconds to store your files in the cache.

8. Disable caching for certain file types

If you don't need to cache certain file types, you can simply leave them out of the list. However, sometimes files can be cached even if you haven't declared them in the list. In such cases, you can disable caching only for these file types. In most cases, you need to disable caching for dynamic files such as scripts. Here's the code:

Header unset Cache-Control

Just add file types that don't need to be cached to the list.

9. Skip the download dialog

By default, when you download a file from a web server, a dialog appears asking you to do something with the file (save or open). This dialog is very annoying when downloading large media files or PDF documents. If the files are uploaded to your server in order for the user to download them, then you can start the process right away. You need to put the following lines in the .htaccess file:

AddType application/octet-stream .pdf AddType application/octet-stream .zip AddType application/octet-stream .mp3

10. Renaming the .htaccess file

For some reasons, usually security related, it may be necessary to rename the .htaccess file. Which is very easy to do. In theory, renaming the .htaccess file should not cause problems with running applications on your server, but if they suddenly appear, you just need to restore the original name.

AccessFileName htac.cess

You also need to update all entries in the file itself and where .htaccess is mentioned, otherwise a lot of errors will arise.

11. Changing the default index page

If you need the index page to be different from the default, index.html, index.php, index.htm, etc., then this task is easy to solve. Here's what you need to add to your .htaccess file:

DirectoryIndex mypage.html

Replace mypage.html with the URL of the page you want.

12. Redirect to a secure https connection

If you are using https and want all users to be redirected to it, then the following code will help you:

RewriteEngine On RewriteCond %(HTTPS) !on RewriteRule (.*) https://%(HTTP_HOST)%(REQUEST_URI)

13. Limiting PHP upload file size, maximum request size and maximum script execution time

Htaccess allows you to set some values ​​that affect PHP applications. For example, if you need to limit downloads in PHP to save hosting space, use the following code:

Php_value upload_max_filesize 15M

Of course you can set the value as required, in our example 15M (MB) is not fixed. You can also limit the maximum request size for uploading in PHP:

Php_value post_max_size 10M

Change 10M to whatever value you require.

If you don't want the script to run forever, you can limit its running time:

Php_value max_execution_time 240

240 - the number of seconds before the script is interrupted.

If you need to limit the time for the script to parse the entered data, use the following line:

Php_value max_input_time 180

14. File type masking

Sometimes you need to hide file types on the server from the user. One way to solve the problem is to disguise them. For example, you can do this. that all files will look like HTML or PHP:

ForceType application/x-httpd-php ForceType application/x-httpd-php

Conclusion

There are many more tasks that .htaccess can solve. For example, you can set automatic translation of site pages, or a time zone, or remove www from the URL, and much more. But before you start experimenting with .htaccess, you should always make a backup copy of the original so that you can return to the source code.