htaccess syntax tutorial apache server pseudo-static rules tutorial_PHP tutorial

WBOY
Release: 2016-07-14 10:11:49
Original
858 people have browsed it

htaccess syntax tutorial apache server pseudo-static rules tutorial

Note: If you are looking for static rules in the Discuz! forum, you don’t need to look here. There is a link in the background of Discuz! and you can just copy it. I don't know about PHPwind. I haven't used it. There should be one in the background.

I have been studying the rewriting rules of Apache these days. Although there are many tutorials on the Internet, I found that most of them were plagiarized from one person and were not complete at all, so I wanted to write a simple and easy-to-understand tutorial. I learned .htaccess starts with directory protection, which is relatively simple. There are also some editors to choose from on the Internet, which I won’t go into here. The tutorial starts with binding a domain name to a subdirectory. There are also tutorials on the Internet, most of which are copied from one person. , let me explain here. 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 you don’t enter a file name, you will be directed to the home page by default

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

RewriteRule^(/)?$blog/index.php[L]

Let me start to explain what it means:

[RewriteEngineOn] means that the rewrite engine is on or off. The function is to conveniently turn on or off the following statements, so that there is no need to comment statements one by one.

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

This is a rewriting condition. The previous %{HTTP_HOST} represents the currently visited URL, which only refers to the prefix part. The format is www.xxx.com excluding "http://" and "/", and ^ represents the beginning of the string. , $ represents the end of the string, . represents escaped., it is fine if not escaped, escaping is recommended to prevent some servers from not supporting it, ? represents the preceding bracket www. appearing 0 or 1 times, the meaning of this rule is If the visited URL is xxx.com or www.xxx.com, execute the following statement. If it does not match, skip it.

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

is also a rewriting condition. %{REQUEST_URI} represents the relative address of the access, which is the address relative to the root directory, which is the component behind the domain name/. The format includes the first "/", ! means non, this statement means The accessed address does not start with /blog/, it just starts with ^ and does not end with $

【RewriteCond%{REQUEST_FILENAME}!-f】

【RewriteCond%{REQUEST_FILENAME}!-d】

The meaning of these two sentences is that the requested file or path does not exist. If the file or path exists, the existing file or path will be returned

[RewriteRule^(.*)$/blog/$1] Rewrite rule, the most important part, means that when the above RewriteCond conditions are met, this rewrite rule will be executed, ^(.*) $ is a regular expression match, matching the current requested URL, ^(.*)$ means matching any character of the current URL, . means any single character, * means matching 0 or N times (N>0), The following /blog/$1 is a rewriting component, which means to rewrite the previously matched characters into /blog/$1. This $1 represents a reverse match and refers to the component of the first parenthesis, that is, ^(.*)$ .* in, actually there will be a problem here, which will be discussed later.

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

【RewriteRule^(/)?$blog/index.php[L]】

The meaning of these two sentences is that the requested host address is www.xxx.com. If there is only 0 or 1 "/" at the end of the address, it will be rewritten to the homepage in the subdirectory. I guess This is mainly because the rewritten address cannot automatically find the homepage and needs to be specified by yourself.

Now let’s talk about the problem. The first part of RewriteRule^(.*)$/blog/$1^(.*)$ will match the current requested URL. For example: the requested URL is http://www.xxx. com/a.html, does it match the entire http://www.xxx.com/a.html, only match /a.html, that is, the component after the backslash, or only match a.html.

The answer is: According to the RewriteBase rules, if rewritebase is /, it will match a.html without the preceding backslash, so the previous statement should be written as RewriteRule^(.*)$blog/$1 (without /), but in practical applications it can also be used with a preceding backslash, possibly with or without it. Now the problem arises. If rewritebase is not set to /, the entire URL http://www.xxx.com/a.html will be matched. Obviously this is wrong, so this should be added:

RewiteBase/

Another problem is that there is no guarantee that the URL entered by everyone is in lowercase. If the URL is entered in uppercase, the Linux system is case-sensitive, so [NC] should be added after RewriteCond to ignore case.

At this point, the complete sentence 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 you don’t enter a file name, you will be directed to the homepage by default

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

RewriteRule^(/)?$blog/index.php[L]

####end####

If there are more sentences after it, you should not add the last [L], because it means the last sentence

To prevent hotlinking, you also need to add RewiteBase/, 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 there are further statements later, the last [L] should not be added. /error/daolian.gif is the picture displayed when others hotlink.

Attached below are simple grammar rules and flags:

[RewriteCond syntax:]

RewriteCondTestStringCondPattern[flags]

Other uses of rewritecond:

‘-d’ (directory)

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

‘-f’ (regular file)

Treat TestString as a pathname and test whether it is a regular file that exists.

‘-s’ (non-empty regular file)

Treat TestString as a pathname and test whether it is an existing regular file with size greater than 0.

‘-l’ (symbolic link)

Treat TestString as a pathname and test whether it is an existing symbolic link.

‘-x’ (executable)

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

‘-F’ (for files that exist in subrequests)

Checks that TestString is a valid file and can be accessed under the server's current access control configuration. It uses an internal subrequest to do the check. It will reduce the performance of the server, so please use it with caution!

‘-U’ (URL for sub-request)

Check that TestString is a valid URL and can be accessed under the server's current access control configuration. It uses an internal subrequest to do the check. It will reduce the performance of the server, so please use it with caution!

[RewriteRule syntax:]

RewriteRulePatternSubstitution[flags]

【flags】:

‘chain|C’(link next rule)

This tag links the current rule to the next rule. It has the effect that if a rule is matched, its successor rules will continue to be processed, that is, this tag will have no effect; if the rule is not matched, its successor rules will be skipped. For example, when performing an external redirect in a directory-level rule, you may need to remove ".www" (".www" should not appear here).

‘cookie|CO=NAME:VAL:domain[:lifetime[:path]]’ (set cookie)

Set a cookie on the client side. The name of the cookie is NAME and the value is VAL. Domain is the domain of the cookie, such as '.apache.org', optional lifetime is the validity period of the cookie (minutes), and optional path is the path of the cookie.


‘env|E=VAR:VAL’ (set environment variable)

This tag sets the value of the environment variable VAR to VAL. VAL can contain expandable regular expression backreferences ($N and %N). This tag can be used multiple times to set multiple variables. These variables can be indirectly referenced in many subsequent situations, usually in XSSI () or CGI ($ENV{'VAR'}), or in subsequent The CondPattern parameter of the RewriteCond directive is referenced by %{ENV:VAR}. Use this to remember information stripped from the URL.

‘forbidden|F’ (forbidden URL)

Forcibly ban the current URL, that is, immediately feedback an HTTP response code 403 (forbidden). Using this tag, you can chain several RewriteConds to conditionally block certain URLs.

‘gone|G’ (forcibly discard URL)

Forcing the current URL to be obsolete, that is, immediately feedback an HTTP response code 410 (obsolete). Use this tag to indicate that the page has been abandoned and no longer exists.

‘handler|H=Content-handler’ (mandatory content handler specification)

Strongly customize the content handler of the target file as Content-handler. For example, the ScriptAlias ​​directive is used to emulate the mod_alias module to force all files within the mapped 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 tag is used to prevent the currently rewritten URL from being rewritten again by subsequent rules. For example, you can use it to rewrite the URL of the root path (‘/’) to an actual URL (for example: ‘/e/www/’).

‘next|N’(start over from the beginning)

Re-execute the rewrite operation (starting over from the first rule). At this time, the URL processed again is no longer the original URL, but the URL processed by the last rewriting rule. It corresponds to the next command in Perl or the continue command in C language. This mark allows the rewrite operation to be restarted (immediately back to the beginning of the loop). But be careful not to create an infinite loop!

‘nocase|NC’(ignore case)

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

‘noescape|NE’ (do not escape URIs in output)

This tag prevents mod_rewrite from applying normal URI escaping rules to the rewrite results. Under normal circumstances, special characters (‘%’, ‘$’, ‘;’, etc.) will be escaped into equivalent hexadecimal encodings (‘%′, ‘$’, ‘;’, etc.). This flag prevents such escaping to allow symbols such as percent signs to appear in the output, such as:

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

Can redirect '/foo/zed' to a safe request '/bar?arg=P1=zed'.

‘nosubreq|NS’ (Do not process internal subrequests)

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

Usage guidelines: If you add a CGI script prefix to URLs to force them to be processed by CGI scripts, but the error rate (or resource overhead) of subrequest processing is high, in this case, you can use this tag .

‘proxy|P’ (forced to be a proxy)

This flag causes the replacement component to be internally forced to be sent as a proxy request, immediately interrupting rewrite processing and handing over processing to the mod_proxy module. You must ensure that this replacement string is a valid URI that can be processed by mod_proxy (such as starting with http://hostname), otherwise you will get an error returned by the proxy module. Using this tag, certain remote components can be mapped to the local server domain name space, thereby enhancing the functionality of the ProxyPass directive.

Note: To use this feature, the mod_proxy module must be enabled.

‘passthrough|PT’ (hand over to next processor)

This tag forces the rewrite engine to set the uri field in the internal request_rec structure to the value of the filename field. This small modification enables the output of the RewriteRule directive to be (converted from URI to filename) Alias, ScriptAlias, Redirect Wait for instructions for subsequent processing [Original text: Thisflagisjustahacktoenablepost-processingoftheoutputofRewriteRuledirectives,usingAlias,ScriptAlias,Redirect,andotherdirectivesfromvariousURI-to-filenametranslators.]. To give an example that illustrates its meaning: 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 part that rewrites uri=/abc/… to filename=/def/… works fine, subsequent mod_alias will encounter failures when trying to convert the URI to a file name.

Note: This tag must be used if you need to mix multiple modules that convert URIs to file names. . Mixing mod_alias and mod_rewrite here is a typical example.

‘qsappend|QSA’ (append query string)

This tag forces the rewrite engine to append a query string to the existing replacement string instead of simply replacing it. You can use this tag if you need to add information to the request string through rewriting rules.

‘redirect|R[=code]‘(force redirection)

If the Substitution starts with http://thishost[:thisport]/ (making the new URL a URI), an external redirect can be forced. If no code is specified, an HTTP response code 302 (Temporary Move) is generated. If you need to use another response code in the 300-400 range, just specify it here (or use one of the following symbolic names: temp (default), permanent, seeother). Use it to feed back the normalized URL to the client, such as rewriting "/~" to "/u/", or always adding a slash to /u/user, etc.

Note: When using this tag, you must ensure that the replacement field is a valid URL. Otherwise, it would point to an invalid location! And keep in mind that this tag itself just prefixes the URL with http://thishost[:thisport]/, the rewriting operation will still proceed. Often, you will also want to stop the rewriting operation and redirect immediately, so you will also need to use the 'L' tag.

‘skip|S=num’ (skip subsequent rules)

This tag forces the rewrite engine to skip num rules after the current matching rule. It can simulate an if-then-else structure: the last rule is a then clause, and the skip=N rules are else clauses. Note: It is different from the 'chain|C' tag!

‘type|T=MIME-type’ (mandatory MIME type)

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

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

【Apache server variable:】

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477293.htmlTechArticlehtaccess syntax tutorial apache server pseudo-static rules tutorial Note: If you are looking for static rules in the Discuz! forum , actually you don’t need to look here, there is a link in Discuz!’s backend...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!