Detailed explanation of apache htaccess file syntax

Source: Internet
Author: User
Tags error code time zones password protection

In Apache. the htaccess file (also known as the "distributed configuration file") provides a method for changing the configuration of directories, that is, to place a file containing commands in a specific document directory, to act on this directory and all its subdirectories. To put it bluntly, the. htaccess file is just a simple document. You can add some simple commands in it to implement various settings.

How do I know whether the host supports. htaccess?

In fact, most hosts support. htaccess, but your host provider does not specifically declare it. Generally, if your host uses Unix, Linux, or any version of Apache network server, it theoretically supports. htaccess, but some host service providers may not allow you to use it. A good way to determine whether your host allows. htaccess is to check whether it supports folder password protection. To achieve this function, the host service provider needs to use. htaccess (of course, although they provide password protection in a few cases, they do not allow you to use. htaccess ). The best way is to upload your own. htaccess file to see if it is useful, or directly consult your host service provider.

What can a. htaccess file do?

. The htaccess file can do a lot of things, including: folder password protection, automatic user redirection, custom error pages, users who change your file extension, ban specific IP addresses, users who only allow specific IP addresses, and list of prohibited directories, and use other files as index files. The following Garden will list several common functions to share with you.

Use the. htaccess file to customize the 404 error page

The most common function of the. htaccess file is to customize the 404 page. The operation is also very simple. Add the code to the. htaccess file:

The code is as follows: Copy code

ErrorDocument 404/Error.html

Create a simple html404 page and name it Error.html
Place Error.html in the root directory of the website. For detailed settings, see how to set the 404 page.

Of course, if your 404 file is not in the root directory of the website, you only need to set the path:

The code is as follows: Copy code

ErrorDocument 404/errors/Error.html

The following lists some of the most common error types on the website:

401-Authorization Required needs verification
400-Bad request error request
403-Forbidden prohibited
500-Internal Server Error
404-Wrong page cannot find the page

You can select a file to create an error, and then define it in the. htaccess file (the method is the same as that on the 404 page), and upload it to your website.

1. Time zone settings


Sometimes, when you use the date or mktime function in PHP, it will display some strange information due to different time zones. The following is one of the solutions to this problem. Is to set the time zone of your server. You can find a list of all supported time zones here.

SetEnv TZ Australia/Melbourne

2. seo/seo.html "target =" _ blank "> search engine-friendly 301 permanent redirection method


Why is this search engine friendly? Because many modern search engines now have the ability to update their existing records permanently based on check 301.

The code is as follows: Copy code

Redirect 301 http://www.111cn.net http://www.111cn.net/

3. Download blocking dialog box


Generally, when you download a file, you will see a dialog box asking whether you want to keep the file or open it directly. If you don't want to see this, you can put the following code in your. htaccess file.

The code is as follows: Copy code

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

4. The www prefix is omitted.

One principle of SEO is to ensure that your website has only one URL. Therefore, you need to turn all the access via www to non-www, or reverse this.

The code is as follows: Copy code

RewriteEngine On
RewriteBase/
RewriteCond % {HTTP_HOST} ^ www111cn.net [NC]
RewriteRule ^ (. *) $ http://cnmiss.cn/#1 [L, R = 301]

5. Personalized Error page
Customize custom error pages for each error code.

The code is as follows: Copy code

ErrorDocument 401/error/401.php
ErrorDocument 403/error/403.php
ErrorDocument 404/error/404.php
ErrorDocument 500/error/500.php

6. Compressed files


By compressing your file volume, you can optimize the website access speed.

The code is as follows: Copy code

# Compressing text, html, javascript, css, and xml:
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
8. AddOutputFilterByType DEFLATE application/rss + xml
9. AddOutputFilterByType DEFLATE application/javascript
10. AddOutputFilterByType DEFLATE application/x-javascript

7. Cache files

Caching files is another good way to speed up your website access.

The code is as follows: Copy code

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

8. Disable caching for certain file types

On the other hand, you can also disable caching for certain file types.

# Explicitly prohibit the use of cache for scripts and other dynamic files

The code is as follows: Copy code
<FilesMatch ". (pl | php | cgi | spl | scgi | fcgi) $">
Header unset Cache-Control
</FilesMatch>

Security questions

The following htaccess code can improve the security level of your web server. Image link theft protection is very useful, it can prevent others from using the image resources on your server.

1. Put leeching through. htaccess
Hate the image resources on your web server that steal links and consume your bandwidth? You can try this to prevent this from happening.

The code is as follows: Copy code

RewriteBase/
RewriteCond % {HTTP_REFERER }! ^ $
RewriteCond % {HTTP_REFERER }! ^ Http: // (www .)? Cnmiss.cn/.*$ [NC]
RewriteRule. (gif | jpg | swf | flv | png) $/feed/[R = 302, L]

2. 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.

The code is as follows: Copy code

RewriteEngine On
 
# Proc/self/environ? No!
RewriteCond % {QUERY_STRING} proc/self/environ [OR]
 
# Prevent the script from attempting to modify the mosConfig value through URL
RewriteCond % {QUERY_STRING} mosConfig _ [a-zA-Z _] {1, 21} (= | % 3D) [OR]
 
# Block base64_encode junk information transmitted by a script through a URL
RewriteCond % {QUERY_STRING} base64_encode. * (. *) [OR]
 
# Block scripts with the <script> flag in the URL
RewriteCond % {QUERY_STRING} (<| % 3C). * script. * (>|% 3E) [NC, OR]
 
# Block scripts that attempt to set the GLOBALS variable of PHP Through URL
RewriteCond % {QUERY_STRING} GLOBALS (= | [| % [0-9A-Z] {0, 2}) [OR]
 
# Block scripts that attempt to set the PHP _ REQUEST variable through URL
RewriteCond % {QUERY_STRING} _ REQUEST (= | [| % [0-9A-Z] {0, 2 })
 
# REDIRECT all blocked requests to the 403 Forbidden prompt page!
RewriteRule ^ (. *) $ index. php [F, L]

3. Block access to your. htaccess file

The following code prevents others from accessing your. htaccess file. You can also block multiple file types.

The code is as follows: Copy code

# Protect your htaccess files
<Files. htaccess>
Order allow, deny
Deny from all
</Files>
 
# Block viewing of specified files
<Files secretfile.jpg>
Order allow, deny
Deny from all
</Files>
 
# Multiple File types
<FilesMatch ". (htaccess | htpasswd | ini | phps | fla | psd | log | sh) $">
Order Allow, Deny
Deny from all
</FilesMatch>

4. Rename the htaccess file

You can rename the htaccess file to protect it.

The code is as follows: Copy code

AccessFileName htacc. ess

5. Disable directory browsing
Disable the server from displaying the directory structure externally, and vice versa.

# Prohibit directory browsing
Options All-Indexes
 
# Open Directory Browsing
Options All + Indexes

6. Change the default Index page
You can change the default index.html, index. php, or index.htm to another page.

DirectoryIndex business.html

7. Block some undesirable viewers by referencing information

The code is as follows: Copy code

# Blocking users from a website
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond % {HTTP_REFERER} scumbag.com [NC, OR]
RewriteCond % {HTTP_REFERER} wormhole.com [NC, OR]
RewriteRule. *-[F]
 
</IfModule>

8. Some requests are blocked by judging the browser header information

This method can save your bandwidth traffic by preventing some robots or spider crawlers from crawling your website.

The code is as follows: Copy code

# Blocking users from certain websites
<IfModule mod_rewrite.c>
SetEnvIfNoCase ^ User-Agent $. * (craftbot | download | extract | stripper | sucker | ninja | clshttp | webspider | leacher | collector | grabber | webpictures) HTTP_SAFE_BADBOT SetEnvIfNoCase ^ User-Agent $. * (libwww-perl | aesop_com_spiderman) HTTP_SAFE_BADBOT Deny from env = HTTP_SAFE_BADBOT
</IfModule>

9. Prohibit script execution to enhance your Directory Security

The code is as follows: Copy code

# Prohibit script execution permissions in some directories
AddHandler cgi-script. php. pl. py. jsp. asp. htm. shtml. sh. cgi
Options-ExecCGI

Use the. htaccess file to protect the website directory password
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 format is:

The code is as follows: Copy code

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 command to. htaccess:

The code is as follows: Copy code

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

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

Note: When you use. htaccess to set 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 way is to add the following command to the. htaccess file:

The code is as follows: Copy code

Order allow, deny
Deny from all

Use the. htaccess file to deny access to an IP address

In fact, this function is also frequently used. Sometimes you may want to prohibit a certain IP address or segment from accessing your website, you can add the following code in. htaccess:

The code is as follows: Copy code

Order allow, deny
Deny from 220.156.156.55
Deny from 220.156.156.
Allow from all

The second line of code is to reject an IP address, and the third line is to reject an IP segment, as long as the IP address is in 220.156.156.0 ~ IP segments before 220.156.156.255 cannot access your site any more. If you want to prevent everyone from accessing this directory, you can use:

The code is as follows: Copy code

Deny from all

Use. htaccess file anti-Leech
Many webmasters may encounter depressing problems, that is, some may often steal images, software, and other resources of their websites, which leads to unnecessary traffic waste. To prevent leeching, add the following command to the. htaccess file:

The code is as follows: Copy code

RewriteEngine on
RewriteCond % {HTTP_REFERER }! ^ $
RewriteCond % {HTTP_REFERER }! ^ Http: // (www .)? Mydomain.com/.#$ [NC]
RewriteRule. (gif & line; jpg) $-[F]

If you want to avoid the unfriendly blank space caused by leeching on your website, you can create an image instead of promoting your website. The command is as follows:

The code is as follows: Copy code

RewriteEngine on
RewriteCond % {HTTP_REFERER }! ^ $
RewriteCond % {HTTP_REFERER }! ^ Http: // (www .)? Mydomain.com/.#$ [NC]
RewriteRule. (gif & line; jpg) $ http://www.mydomain.com/replace the image file name [R, L]

Use the. htaccess file to change the default homepage file
This is also quite common. If your site is structured in PHP, you can just define index. php as the default homepage file, which can be easily achieved through the. htaccess file. The code is as follows:

The code is as follows: Copy code

DirectoryIndex index. php index. php3 messagebrd. pl index.html index.htm

The server searches from left to right to check which document exists in your website directory. The first file is the default homepage file of your website.

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: info-contact@alibabacloud.com 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.