Htaccess syntax tutorial apache server pseudo-static rules tutorial

Source: Internet
Author: User
Tags set cookie

Htaccess syntax tutorial apache server pseudo-static rules tutorial

Note: If you are looking for Discuz! If the Forum has static rules, you don't need to read them here. Discuz! There is a link in the background to Copy it directly. I don't know about PHPwind. I have never used PHPwind. I should have it in the background.

I have been studying Apache rewrite rules over the past few days. Although there are many tutorials on the internet, I find that most of them are copied from one person, but they are not all at all. So I want to write a simple and easy-to-understand tutorial, I learned. 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 domain names to subdirectories. There are also tutorials on the Internet, most of them copy a person. Here I will explain that the tutorial is written like this:

RewriteEngineOn

RewriteCond % {HTTP_HOST} ^ (www \.)? Xxx \. com $

RewriteCond % {REQUEST_URI }! ^/Blog/

RewriteCond % {REQUEST_FILENAME }! -F

RewriteCond % {REQUEST_FILENAME }! -D

RewriteRule ^ (. *) $/blog/$1

# If no file name is input, it is sent to the homepage by default.

RewriteCond % {HTTP_HOST} ^ (www \.)? 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 ####

RewriteEngineOn

RewiteBase/

RewriteCond % {HTTP_HOST} ^ (www \.)? Xxx \. com $ [NC]

RewriteCond % {REQUEST_URI }! ^/Blog/

RewriteCond % {REQUEST_FILENAME }! -F

RewriteCond % {REQUEST_FILENAME }! -D

RewriteRule ^ (. *) $ blog/$1

# If no file name is input, it is sent to the homepage by default.

RewriteCond % {HTTP_HOST} ^ (www \.)? 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:

RewriteEngineon

RewiteBase/

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 (<! -# Echovar = "VAR"->) or CGI ($ ENV {'var'}), you can also use % {env in the CondPattern parameter of the subsequent RewriteCond command: VAR} references. 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]

[Apache server variable :]

 

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.