Apache server pseudo-static rules tutorial _ htaccess

Source: Internet
Author: User
Tags response code set cookie
Htaccess syntax tutorial apache server pseudo-static rules tutorial Htaccess syntax tutorial apache server pseudo-static rules tutorial
Although there are many tutorials on the Internet, they are not all found at all. so I want to write a simple and easy-to-understand tutorial. htaccess is started from directory protection. this is also relatively simple. some editors can be selected on the internet. I will not talk about it here. the tutorial starts from binding a domain name to a subdirectory. The tutorial is written like this:

RewriteEngineOnRewriteCond % {HTTP_HOST} ^ (www \.)? Xxx \. com $ RewriteCond % {REQUEST_URI }! ^/Blog/RewriteCond % {REQUEST_FILENAME }! -FRewriteCond % {REQUEST_FILENAME }! -DRewriteRule ^ (. *) $/blog/$1 # if no file name is input, the system returns to the homepage RewriteCond % {HTTP_HOST} ^ (www \.) by default \.)? Xxx \. com $ RewriteRule ^ (/)? $ Blog/index. php [L]

Next I will explain the above:

[RewriteEngineOn] indicates that the rewrite engine is enabled and off. The function is to enable or disable the following statements conveniently, so that a comment statement is not required.

【RewriteCond%{HTTP_HOST}^(www\.)?xxx\.com$】

This is a rewrite condition. the preceding % {HTTP_HOST} indicates the current website address, which only refers to the prefix. the format is www.xxx.com and does not include "http: //" or "/". ^ indicates the start of the string, $ indicates the end of the string ,\. escape ., if you do not want to escape it, we recommend that you escape it to prevent some servers from not supporting it ,? It indicates that www \. appears 0 times or 1 time in front of the brackets. this rule means that if the URL accessed is xxx.com or www.xxx.com, the following statement is executed. if the URL does not match, the statement is skipped.

【RewriteCond%{REQUEST_URI}!^/blog/】

It is also a rewriting condition. % {REQUEST_URI} indicates the relative address of the access, that is, the address of the relative root directory, that is, the domain name/the following component. the format includes the first "/",! This statement indicates that the access address does not start with/blog/, but starts with ^ and does not end with $

【RewriteCond%{REQUEST_FILENAME}!-f】【RewriteCond%{REQUEST_FILENAME}!-d】

The two statements mean that the requested file or path does not exist. if the file or path exists, an existing file or path will be returned.

[RewriteRule ^ (. *) $/blog/$1] rewrite rule. The most important part is that when all the RewriteCond conditions are met, the rewrite rule will be executed. ^ (. *) $ is a regular expression match, matching the URL of the current request, ^ (. *) $ indicates matching any character of the current URL ,. represents any single character. * indicates that the string matches 0 or N times (N> 0), followed by/blog/$1 as the rewriting component, it means to rewrite the matched character to/blog/$1. this $1 indicates reverse matching and references the component of the first parentheses, that is, ^ (. *) $. * In fact, there will be a problem, which will be discussed later.

【RewriteCond%{HTTP_HOST}^(www\.)?xxx\.com$】【RewriteRule^(/)?$blog/index.php[L]】

The two statements mean that the requested host address is www.xxx.com. if there are only 0 or 1 "/" at the end of the address, it will be rewritten to the home page under the subdirectory, I guess this is mainly because the rewritten address cannot automatically search for the home page, and you need to specify it yourself.

Now let's talk about the problem. The first part of RewriteRule ^ (. *) $/blog/$1 ^ (. *) $ will match the url of the current request. for example, the request url is.

The answer is: according to the RewriteBase rules, if rewritebase is/, it will match a.html without the front backslash. Therefore, the previous statement should be written as RewriteRule ^ (. *) $ blog/$1 (without/), but it can also be used to bring the forward backslash in actual applications. Now the problem arises. if rewritebase is not set to/, the whole website will be matched at http://www.xxx.com/a.html. this is an error, and the corresponding rewritebase should be:

RewiteBase

Another problem is that each user cannot input a URL in lowercase. if the URL is entered in uppercase, the linux system is case sensitive, therefore, [NC] should be added after RewriteCond to ignore case sensitivity.
At this point, the complete statement should be:

#### Start #### RewriteEngineOnRewiteBase/RewriteCond % {HTTP_HOST} ^ (www \.)? Xxx \. com $ [NC] RewriteCond % {REQUEST_URI }! ^/Blog/RewriteCond % {REQUEST_FILENAME }! -FRewriteCond % {REQUEST_FILENAME }! -DRewriteRule ^ (. *) $ blog/$1 # if no file name is input, the page will be RewriteCond % {HTTP_HOST} ^ (www \.) by default \.)? Xxx \. com $ [NC] RewriteRule ^ (/)? $ Blog/index. php [L] #### end ####

If the statement is still followed, the last [L] should not be added, because this indicates the meaning of the last statement.

RewiteBase/must be added to the anti-Leech statement as follows:

RewriteEngineonRewiteBase/RewriteCond%{HTTP_REFERER}!^$[NC]RewriteCond%{HTTP_REFERER}!xxx.info[NC]RewriteRule\.(jpg|gif|png|bmp|swf|jpeg)$/error/daolian.gif[R,NC,L]

If the statement is still followed, the final [L] and/error/daolian.gif should not be added as the image displayed when someone else leeching.

The following are simple syntax rules and flags:

[RewriteCond syntax :]

RewriteCondTestStringCondPattern[flags]


Other usage of rewritecond:

'-D' (directory)

Treat TestString as a path name and test whether it is an existing directory.

'-F' (regular file)

Treat TestString as a path name and test whether it is an existing regular file.

'-S' (non-empty regular files)

Consider TestString as a path name and test whether it is an existing regular file with a size greater than 0.

'-L' (symbolic join)

Treat TestString as a path name and test whether it is an existing symbolic connection.

'-X' (executable)

Treat TestString as a path name and test whether it is an existing file with executable permissions. This permission is detected by the operating system.

'-F' (the file that exists in the subrequest)

Check whether TestString is a valid file and can be accessed under the current access control configuration of the server. It uses an internal sub-request for Check. please use it with caution because it will reduce the server performance!

'-U' (the URL of the child request)

Check whether TestString is a valid URL and can be accessed under the current access control configuration of the server. It uses an internal sub-request for Check. please use it with caution because it will reduce the server performance!

[RewriteRule syntax :]

RewriteRulePatternSubstitution [flags]

[Flags ]:

'Chain | C' (link to the next rule)

This flag links the current rule to the next rule. It produces the following effect: if a rule is matched, the subsequent rule is processed, that is, the tag does not work. if the rule is not matched, the subsequent rules are skipped. For example, when executing an external redirection in a directory-level rule, you may need to delete ". www" (". www" should not appear here ").

'Cookie | CO = NAME: VAL: domain [: lifetime [: path] '(set cookie)

Set a cookie on the client. The cookie NAME is NAME and the value is VAL. Domain is the cookie's domain, such as '.apache.org'. the optional life time is the cookie's validity period (in minutes), and the optional path is the cookie's path.

'Env | E = VAR: VAL '(set environment variables)

This flag sets the environment variable VAR value to VAL, which can contain extensible regular expressions for reverse reference ($ N and % N ). This tag can be used multiple times to set multiple variables. These variables can be indirectly referenced in many cases, usually in XSSI ( ) Or CGI ($ ENV {'var'}), you can also reference it through % {ENV: VAR} in the CondPattern parameter of the subsequent RewriteCond command. You can use it to remember the information stripped from the URL.

'Forbidden | f' (forcibly forbid URLs)

The current URL is forcibly forbidden, that is, an HTTP response code 403 (forbidden) is immediately reported ). With this tag, you can link several RewriteConds to block certain URLs with conditions.

'Gone | g' (forcibly deprecated URL)

Force the current URL to be obsolete, that is, an HTTP response code 410 (obsolete) is immediately reported ). Use this tag to indicate that the page has been deprecated and does not exist.

'Handler | H = Content-handler' (mandatory Content processor)

The Content processor of the target file is Content-handler. For example, it is used to simulate the ScriptAlias command of the mod_alias module to force all files in the ing folder to be processed by the cgi-script processor.

'Last | L' (ending rule)

Stop the rewrite operation immediately and no other rewrite rules will be applied. It corresponds to the last command in Perl or the break command in C language. This flag is used to prevent a URL that has been rewritten from being overwritten by a subsequent rule. For example, you can use it to rewrite the root path URL ('/') to an existing URL (for example, '/e/www /').

'Next | n' (start from scratch)

Re-execute the rewrite operation (starting from the first rule ). At this time, the URL processed again is not the original URL, but the URL processed by the last rewrite rule. It corresponds to the next command in Perl or the continue command in C language. This flag allows you to re-start the rewrite operation (immediately return to the beginning of the loop ). But be careful not to create an endless loop!

'Nocase | NC '(case insensitive)

It makes Pattern case insensitive, that is, when Pattern matches the current URL, there is no difference between 'a-Z' and 'A-Z.

'Noescape | NEE' (do not escape the URI in the output)

This flag prevents mod_rewrite from applying regular URI escape rules to rewrite results. In general, special characters ('%', '$', ';', etc.) are escaped as equivalent hexadecimal encoding ('%', '$ ′, ';', etc ). This mark can prevent such escaping to allow symbols such as percent signs to appear in the output, for example:

RewriteRule/foo/(. *)/bar? Arg = P1 \ = $1 [R, NE]

Can '/foo/zed be redirected to a secure request'/bar? Arg = P1 = zed '.

'Nosubreq | NS' (internal subrequests are not processed)

When the current request is an internal subrequest, This flag forces the rewrite engine to skip this rewrite rule. For example, when mod_include tries to search for the default directory file (index. xxx), Apache will generate a subrequest internally. For a subrequest, the rewrite rule is not necessarily useful. if the entire rule set takes effect, it may even cause an error. Therefore, you can use this tag to exclude certain rules.

Usage principle: if you add a CGI script prefix to the URL to force them to be processed by the CGI script, but the error rate (or resource overhead) of the sub-request processing is very high, in this case, you can use this tag.

'Proxy | P' (forced as a proxy)

This flag forces the replacement component internally to be sent as a proxy request, and immediately interrupts the rewrite processing, and then transfers the processing to the mod_proxy module. You must ensure that the replacement string is a valid URI that can be processed by mod_proxy (for example, starting with http: // hostname). Otherwise, an error will be returned by the proxy module. Using this tag, you can map some remote components to the domain name space of the local server, thus enhancing the ProxyPass command function.

Note: To use this function, you must have enabled the mod_proxy module.

'Passthrough | pt' (handed over to the next processor)

The force rewrite engine sets the uri field in the internal request_rec structure as the value of the filename field. this small modification allows the output of the RewriteRule command to be (converted from URI to file name) Alias, scriptAlias, Redirect and other commands for subsequent processing [original: Thisflagisjustahacktoenablepost-encoding, usingAlias, ScriptAlias, Redirect, andotherdirevesfromvariousuri-to-filenametranslators.]

For example, if you want to rewrite/abc to/def and then use mod_alias to convert/def to/ghi, you can do this:

RewriteRule ^/abc (. *)/def $1 [PT]

Alias/def/ghi

If the PT tag is omitted, although the uri =/abc /... Rewrite to filename =/def /... But the subsequent mod_alias attempts to convert the URI to the file name will fail.

Note: If you need to use multiple modules to convert URIs to file names, you must use this tag .. The mixed use of mod_alias and mod_rewrite is a typical example.

'Qsappend | qsa' (append query string)

This flag forces the rewrite engine to append a query string to an existing replacement string, instead of simply replacing it. If you need to add information to the request string by using the rewrite rule, you can use this flag.

'Redirect | R [= code] '(force redirect)

If the Substitution starts with http: // thishost [: thisport]/(to make the new URL a URI), an external redirection can be executed forcibly. If no code is specified, an HTTP response code 302 (temporary movement) is generated ). To use other response codes in the range of-, you only need to specify them here (or use one of the following Symbol names: temp (default), permanent, seeother ). The canonicalized URL can be fed back to the client, for example "/~" Rewrite it to "/u/", or always add a slash to/u/user, and so on.

Note: When using this tag, make sure that the field to be replaced is a valid URL. Otherwise, it will point to an invalid location! Remember that this flag only adds the http: // thishost [: thisport]/prefix to the URL, and the rewrite operation will continue. Generally, if you want to stop the rewrite operation and redirect immediately, you also need to use the 'L' flag.

'Skip | S = num' (skip the successor rule)

This flag forces the rewrite engine to skip the num rules after the current matching rule. It can simulate the if-then-else structure: The last rule is the then clause, and the skipped skip = N rules are the else clause. Note: it is different from the 'chain | c' mark!

'Type | T = MIME-type' (mandatory MIME type)

The MIME type of the target file is forced to be MIME-type, which can be used to forcibly set the content type based on certain conditions. For example, the following command enables the. PHP file to be displayed by mod_php according to the php source code MIME type (application/x-httpd-PHP-source) when the. php file is called with the. phps extension:

RewriteRule^(.+\.php)s$$1[T=application/x-httpd-php-source]

Related articles: differences between pseudo-static, static, and dynamic, and various pseudo-static setting methods

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.