Common rules and examples of. htaccess files

Source: Internet
Author: User
Tags password protection to domain

. The htaccess file is an important configuration file in Apache. Its format is plain text. It provides a method for changing the configuration of directories, you can place a file containing one or more commands in a specific document directory to act on this directory and all its subdirectories.

Pass. the htaccess file can implement many simple functions that are cumbersome or even unable to be implemented in IIS, such as password protection, prohibiting the display of directory lists, blocking/allowing specific IP addresses, and implementing 301 redirection of the website.

1. Redirect 301

For the purpose of SEO and website conversion, we need to use 301 redirection during initial website creation or website migration, usually includes domain name to domain name, directory to directory and one independent Web site to another independent Web site redirection. Perform 301 redirection on a Linux vm. The most common method is to directly edit the. htaccess file or use cPanel. Essentially, the essence of the two is to modify the. htaccess file. Here we mainly talk about the first method to directly edit the. htaccess file.

To redirect to to make the domain name unique, open the. htaccess file and add the following code:

RewriteEngine On
RewriteCond % {HTTP_HOST }! ^ $ [NC]
RewriteRule ^ (. *) $ [L, R = 301]

To redirect a file, use to B .com/file/fileb.php, and add the following code only:

RewriteCond % {HTTP_HOST} ^ $
RewriteRule ^ file/file. php $ http://www. B .com/file/fileB.php [R = 301, L]

2. Anti-Leech

The so-called leeching refers to the files directly linked to our website by other websites. Generally, the leeching objects are mostly large-volume files with high bandwidth consumption, such as images and videos. In this way, the server traffic is easily burdened, thus affecting the website access speed. To ensure that our website traffic can be fully utilized by ourselves, we can modify it. set anti-Leech for the htaccess file to restrict files from being referenced by external sites. You only need to open the file. add the following code to the htaccess file:

RewriteEngine on
RewriteCond % {HTTP_REFERER }! ^ $ [NC]
RewriteCond % {HTTP_REFERER }! [NC] // This line sets the HTTP source that can be accessed, including the website itself. You can also write another line to change the domain name to baidu or Google.
RewriteRule. *. (gif | jpg | png) $-[F] // The format can be deleted and modified according to different situations, such as mp3 and rar. Separate the formats with '"|.

3. Block/allow specific IP addresses

In some cases, you may only want to allow users with certain IP addresses to access your website, or block certain IP addresses. Of course, this is only useful when you know the IP address you want to intercept. However, most users on the Internet use dynamic IP addresses, so this is not a common method to restrict the use of dynamic IP addresses:

1. You can use the following command to block an IP address:

Deny from
Here, is the banned IP address. If you specify only a few of them, you can block the IP address of the entire network segment. If you enter 210.10.56., ~ All IP addresses of


2. You can also use the following command to allow an IP address to access the website:

Allow from
The allowed IP address is You can allow the entire network segment like the banned IP address.
3. If you want to prevent/allow everyone to access this directory, you can use:
Deny from/allow from all

4. Custom error page

One application of htaccess is a custom error page, which enables you to have your own personalized error page (for example, when a file cannot be found ), instead of the error pages provided by your service provider or without any pages. This will make your website look more professional when an error occurs. You only need to add the following code to the. htaccess file to customize several common errors:

ErrorDocument 400/errors/badrequest.html // Bad request error request

ErrorDocument 401/errors/authreqd.html // Authorization Required needs verification

ErrorDocument 403/errors/forbid.html // Forbidden

ErrorDocument 404/errors/notfound.html // the Wrong page cannot be found.

ErrorDocument 500/errors/serverr.html // Internal Server Error

5. Compressed files

By compressing the volume of your files (text, html, JavaScript, css, xml, etc.) to optimize the website access speed, this is very useful for many webmasters who want to increase the website access speed, you only need. add the following code to the htaccess file:

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml + xml
AddOutputFilterByType DEFLATE application/rss + xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
6. Cache or disable caching of some files

Caching files is another good way to speed up your website access. You only need to add the following code to the. htaccess file:

# <FilesMatch ". (flv | gif | jpg | jpeg | png | ico | swf | js | css | pdf) $">
Header set Cache-Control "max-age = 2592000 & Prime;

On the other hand, you can also customize to disable caching for certain file types:

<FilesMatch ". (pl | php | cgi | spl | scgi | fcgi) $">
Header unset Cache-Control

7. The WWW prefix is omitted.

One principle of SEO is to ensure that your website has only one URL. Therefore, you need to add the following code in the. htaccess file to implement all non-www accesses that are switched to through www, or vice versa:

RewriteEngine On
RewriteCond % {HTTP_HOST} ^ www. aips. me [NC]
RewriteRule ^ (. *) $ [L, R = 301]
8. Anti-hacker

If you want to improve the security level of your website, you can add the following lines of code to prevent some hacker attack techniques that match common malicious URLs:

RewriteEngine On

RewriteCond % {QUERY_STRING} proc/self/environ [OR] // proc/self/environ? No Way!

RewriteCond % {QUERY_STRING} mosConfig _ [a-zA-Z _] {} (=|\% 3D) [OR] // prevents the script from attempting to modify the mosConfig value through URL

RewriteCond % {QUERY_STRING} base64_encode. * (. *) [OR] // block base64_encode junk information transmitted by the script through the URL

RewriteCond % {QUERY_STRING} (<| % 3C). * script. * (>|% 3E) [NC, OR] // block the script containing the <script> flag in the URL

RewriteCond % {QUERY_STRING} GLOBALS (= | [| \ % [0-9A-Z] {0, 2}) [OR] // block scripts that attempt to set the GLOBALS variable of PHP Through URL

RewriteCond % {QUERY_STRING} _ REQUEST (= | [| \ % [0-9A-Z] {0, 2}) // block scripts that attempt to set the PHP _ REQUEST variable through URL

RewriteRule ^ (. *) $ index. php [F, L] // redirect all blocked requests to the 403 Forbidden page

9. Do not display the directory list

Sometimes, there is no default index file in your Directory. When someone accesses this directory in the browser address bar, all the files in the directory will be displayed, which leaves a security risk for your website. To avoid this situation (instead of creating a bunch of new index files), you can add the following code to the. htaccess file to prevent the display of the directory list:


10. Correct code encoding

The developer knows that if the page is gb2312 encoded and the B page is UTF-8 encoded, if the page include references B Page, garbled characters are generated and can be used. htaccess is a webpage correction code: many friends often encounter garbled characters after writing a piece of code and uploading it to the server. The following steps will solve the problem of garbled code due to code encoding:

<FilesMatch "\. (htm | html | css | js) $">

Adddefacharcharset UTF-8

11. Implement website directory password protection

Sometimes you may set the password protection for a directory. The first thing you need to do is to generate a. htpasswd document, and then enter the user name and password used to access the website. The code is:

Username: password

The "password" must be an encrypted password. In addition, it should be noted that the location of the. htpasswd document is preferably outside the www directory, which is relatively safer.

Add the following code to the. htaccess file:

AuthUserFile/full/path/to/. htpasswd // server directory of. htpasswd
AuthGroupFile/dev/null // directory to be authorized to access
AuthName EnterPassword
AuthType Basic // authorization type
Require valid-user

This completes the use of the. htaccess file to implement website directory password protection.

In addition, when you use. htaccess to set the password protection for a directory, it contains the path of the password file. In terms of security, it is necessary to protect. htaccess from being visible to others. The simplest method is to add the following code to the. htaccess file:

Order allow, deny
Deny from all

We hope that the usage of the. htaccess file can help you, and you are welcome to share some of the other usage tips on. htaccess files that have not been mentioned above.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.