Apache. htaccess file detailed understanding and Configuration Tips Summary

Source: Internet
Author: User
Tags time zones block ip address password protection
I. Basic role of htaccess

. htaccess is a plain text file that contains instructions related to Apache server configuration.
The main functions of the. htaccess are URL rewriting, custom error pages, MIME type configuration, and access control. Mainly embodied in pseudo-static applications, image anti-theft chain, custom 404 error page, block/allow specific IP/IP segment, Directory Browsing and home page, prohibit access to the specified file type, file password protection, etc.
The purpose of the. htaccess range is primarily for the current directory.


Second, enable the configuration of the. htaccess
Enable. htaccess, you need to modify httpd.conf, enable allowoverride, and use allowoverride to limit the usage of specific commands.
After opening the httpd.conf file with a text editor open, look for

Copy the code code as follows:

<directory/>options followsymlinksallowoverride none</directory> instead: <directory/>Options Followsymlinksallowoverride all</directory>


If you need to use a file name other than. htaccess, you can use the Accessfilename directive to change it. For example, if you need to use. config, you can configure it in the server configuration file in the following ways:

Copy the code code as follows:

Accessfilename. config

Iii.. htaccess access Control

1. Access Control Basics: Order command

In order to restrict access to some critical directories, it is common to add. htaccess files, which are commonly written as follows:

Copy the code code as follows:

<files  ~ "^.*\." ( [Ll] [Oo] [Gg]) | ([Ee][xx][ee]) "> Order Allow,deny deny from all</files>

Description

(1) The wavy line after Files indicates that "regular expression" is enabled, and the simple wording is: <files *>.

(2) Order command: With the Allow,deny parameter, Apache first finds and applies the Allow command, and then applies the Deny command to block all access, or you can use Deny,allow.

Iv. URL Rewriting

Here is an example of a simple URL rewrite rule:

Copy the code code as follows:


# Open the Rewriteengine mode
Rewriteengine on
# Rewrite System rules do not modify
Rewriterule ^p/([0-9]+) \.html$ index.php?post_id=$1
Rewriterule ^u-(Username|uid)-(. +) \.html$ space.php?$1=$2


Where rewriteengine means to turn on URL rewriting, rewriterule is a rewrite rule.

Five, configuration error page

The basic syntax is as follows:

Copy the code code as follows:

# custom Error documentserrordocument 401/err/401.phperrordocument 403/err/403.phperrordocument 404/err/404. Phperrordocument 500/err/500.php

Vi. htaccess common commands and configuration tips
1. Disable display of directory listings
Sometimes, for some reason, there is no index file in your directory, which means that when someone types the path to the directory in the browser's address bar, all the files in that directory will be displayed, which will leave your site with a security risk.
To avoid this situation (without having to create a bunch of new index files), you can type the following command in your. htaccess document to block
Display of directory Listings:

Copy the code code as follows:

Options-indexes


2. Block/allow a specific IP address
In some cases, you may want to allow only certain IP users to access your website (for example, only users with a particular ISP are allowed to enter a directory), or to block certain IP addresses (for example, to isolate low-level users from your information layout). Of course, this is only useful if you know the IP address you want to intercept, but now most users on the Web use dynamic IP addresses, so this is not a common method of limiting usage.
You can use the following command to block an IP address:

Copy the code code as follows:

Deny from 000.000.000.000


The 000.000.000.000 here is the banned IP address, and if you specify only a few of them, you can block the entire network segment address. If you enter 210.10.56., all IP addresses of the 210.10.56.0~210.10.56.255 will be blocked.
You can use the following command to allow an IP address to access a Web site:

Copy the code code as follows:

Allow from 000.000.000.000


The allowed IP address is 000.000.000.000, you can allow the entire network segment like a block IP address.
If you want to prevent everyone from accessing the directory, you can use:

Copy the code code as follows:

Deny from all


However, this does not affect the script to use the document under this directory.
3. Replace the index file
Maybe you don't want to always use index.htm or index.html as the index file for the directory. For example, if your site uses PHP files, you might want to use index.php as the index document for that directory. Of course, it doesn't have to be limited to the "index" document, if you want to, use. htaccess you can even set Foofoo.balh as your index document!
These alternate index files can be lined up in a list, and the server looks from left to right to check which documents exist in the real directory. If one is not found, it will display the list of directories (unless you have closed the list of displayed directory files).

Copy the code code as follows:

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


4. Redirection (rewrite)
One of the most useful features of the. Htaccess is redirecting requests to different documents within or outside the same station. This is extremely useful when you change a file name, but still want the user to have access to it with the old address. Another application (which I found useful) was to redirect to a long URL, for example, in my newsletter, I could use a very short URL to point to my affiliate link. The following is an example of a redirected file:

Copy the code code as follows:

Redirect/location/from/root/file.ext http:    ///new/file/location.xyz


In the example above, access to the root directory named oldfile.html can be typed:

Copy the code code as follows:

/oldfile.html
To access a file in an old secondary directory, you can type:

/old/oldfile.html


You can also use. htaccess to redirect the entire site's directory. If you have a directory named OldDirectory on your website and you have created the same document on a new website http:///newdirectory/, you can redirect all files in the old directory once without having to one by one declare:

Copy the code code as follows:

Redirect/olddirectory http:///newdirectory


Thus, any request to the/olddirectory directory in the site will be re-directed to the new site, including additional additional URL information. For example someone typed:


http:///olddirecotry/oldfiles/images/image.gif
The request will be redirected to:

http:///newdirectory/oldfiles/images/image.gif


If used correctly, this feature will be extremely powerful.

Vii. Security Configuration
The following htaccess code can improve the security level of your Web server. Image link theft protection is useful to prevent others from stealing image resources on your server.
1. Put hotlinking through. htaccess
Hate the behavior of stealing the image resources on your Web server and draining your bandwidth? Try this, you can prevent this kind of thing from happening.

Copy the code code as follows:

Rewritebase/  Rewritecond%{http_referer}!^$  rewritecond%{http_referer}!^http://(www.)? php.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 remove the following lines of code, which will prevent some common malicious URLs from being matched by hacker attack techniques.

Copy the code code as follows:

Rewriteengine on  # Proc/self/environ?  Rewritecond%{query_string} proc/self/environ [OR]  # block script attempts to modify Mosconfig value via URL  rewritecond%{query_ STRING} mosconfig_[a-za-z_]{1,21} (=|%3d) [OR]  # block script base64_encode spam messages passed through URL  rewritecond%{query_string} Base64_encode.* (. *) [OR]  # blocks script  Rewritecond%{query_string} (<|%3c) that contains <script> tags in the URL. *script.* ( >|%3E) [Nc,or]  # block attempts to set PHP GLOBALS variables by URL script  rewritecond%{query_string} GLOBALS (=|[| %[0-9a-z]{0,2}) [OR]  # block the script that attempts to set PHP's _request variable by URL  rewritecond%{query_string} _request (=|[| %[0-9a-z]{0,2})  # turn all blocked requests to the 403 Forbidden prompt page!  rewriterule ^ (. *) $ index.php [f,l]


3. Block access to your. htaccess file or a file of the specified type
The following code can prevent someone from accessing your. htaccess file. Similarly, you can also set block multiple file types.

# Protect your htaccess file  <files .htaccess>  order Allow,deny deny from all  </Files>  # Prevents viewing of the specified file  <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 >[/code]

4. Prohibit script execution and enhance your directory security

Copy the code code as follows:

# Disable script execution permissions in some directories  AddHandler cgi-script. php. pl. py. jsp. asp. htm. shtml. Sh. CGI  options-execcgi


Viii. some common settings
1. Time zone settings
Sometimes, when you use the date or Mktime function in PHP, it shows some strange information because of the time zone difference. Here is one way to solve this problem. is to set the time zone of your server. You can find a list of all supported time zones here.
1.SETENV TZ Australia/melbourne
2. seo/seo.html "target=" _blank "> Search Engine Friendly 301 Permanent steering method
Why is this search engine friendly? Because many modern search engines now have the ability to update their existing records according to the Check 301 permanent turn.

Copy the code code as follows:

Redirect 301 http:    //www.php.cn/article/index http:    //www.php.cn/article/


3. Block the Download dialog box
Usually, when you download something, you'll see a dialog box asking if you'd like to keep the file or open it directly. If you don't want to see this, you can put the following piece of code in your. htaccess file.

Copy the code code as follows:

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


4. Omit WWW prefixes
One of the principles of SEO is to make sure that your site has only one URL. Therefore, you need to turn all the access through the WWW to non-www, or reverse this.

Copy the code code as follows:

Rewriteengine on  rewritebase/  rewritecond%{http_host} ^www.php.cn [NC]  rewriterule ^ (. *) $ HTTP:    // www.php.cn/$1 [l,r=301]


5. Personalize the error page
Customize your own error page for each error code.

Copy the code code as follows:

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


6. Compressing files
Optimize your website's access speed by compressing your file volume.

Copy the code code as follows:

# compressed text, HTML, JavaScript, CSS, 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  Addoutputfilterbytype DEFLATE application/rss+xml  addoutputfilterbytype DEFLATE application/javascript  . Addoutputfilterbytype DEFLATE Application/x-javascript


7. cache files
Caching files is another good way to improve your website's speed of access.

Copy the code code as follows:

<filesmatch ". (flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf) $ ">  Header set Cache-control" Max-age=2592000″  </ Filesmatch>


8. Disable the use of caching for certain file types
On the other hand, you can also customize the use of caching for certain file types.

Copy the code code as follows:

# Explicit rules prohibit the use of cache <filesmatch for scripts and other dynamic Files  ". ( pl|php|cgi|spl|scgi|fcgi) $ ">  Header unset cache-control  </FilesMatch>
  • 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.