. htaccess syntax and application

Source: Internet
Author: User
Tags deprecated id3 passthrough response code

Go

Http://blog.sina.com.cn/s/blog_6e8b46e701014drc.html

Http://blog.sina.com.cn/s/blog_6e8b46e701014dtu.html

. htaccess is a very powerful distributed configuration file for Apache servers. The correct understanding and use of. htaccess files can help us optimize our own servers or virtual hosts.

How to enable htaccess take windows as an example, go to the apache/conf directory, find the httpd.conf file, remove the # LoadModule Rewrite_module modules/mod_rewrite.so Front, Then set directory properties allowoverride all, restart Apache

Common formats

The following is a typical htaccess file

# Turn on URL rewriting
Rewriteengine on
# Scope of URL overrides
# Rewritebase/path/to/url
# What conditions to meet
Rewritecond%{http_host}!^www\.example\.com$ [NC]

# What rules to apply
Rewriterule.? Http://www.example.com%{request_uri} [R=301,l]

Take a look at Rewritecond, first there is a%, because {http_host} is an Apache variable that needs to be indicated by%. Starting from! is the matching condition, which supports the regular. The meaning is not equal, this sentence means: If http_host is not www.example.com. The following [NC] (no case) indicates ignoring casing, and common

    • L (last): Terminates a series of Rewritecond and Rewriterule
    • R (redirect): Triggers a displayed jump, or you can specify a jump type, such as [r=301]
    • F (Forbidden): Disable viewing of specific files, Apache will trigger 403 error

Typical applications

Picture anti-theft chain

Rewritecond%{http_referer}!^$
Rewritecond%{http_referer}!^http://(www\.)? example\.com/[NC]
Rewriterule \. (gif|jpg|png) $-[F]

Because it is based on http_referer verification, it can only prevent the general picture hotlinking, because Http_referer is relatively easy to forge

Customizing the 404 error page
If the user enters a URL that does not exist, the custom error page is displayed

ErrorDocument 404/404.html
# Other Empathy
ErrorDocument 500/500.html

Working with moved Files

Redirect 301/old.html http://yoursite.com/new.html
# It could be the following
Rewriterule/old.html http://yoursite.com/new.html [r=301,l]
# If you want to have an implicit jump (the URL address is the same, but the content is actually a different URL), use the following
Rewriterule/old.html http://yoursite.com/new.html [L]

There are a lot of articles that can be done for rewriterule, such as

# link HTML suffix URL to php file
# is referring to the previous 1th bracketed content
Rewriterule ^/? ([a-z/]+) \.html$ $1.php [L]
# or link the contents of the old folder to the new folder
Rewriterule ^/?old_directory/([a-z/.] +) $ new_directory/$1 [r=301,l]
# Hide file names
Rewriterule ^/? ([a-z]+) $ $1.php [L] Suppress directory listing

If there is no index file in the directory, and the directory has not been specifically processed, especially the Windows host, then the contents of the directory will be displayed, you can create a. htaccess file in the root directory, and then write

Options-indexes
# That's the way it's done

Block/allow specific IP/IP segments

# All IPs are forbidden except for the specified
Order Deny,allow
Deny from all
# If you want to allow IP segments, such as 123.123.123.0 ~ 123.123.123.255, then
# Allow from 123.123.123.
Allow from 123.123.123.123

ErrorDocument 403/page.html


Allow from all


#如果想禁止特定IP
Deny from 123.123.123.123

Add MIME type

AddType video/x-flv. flv
# If the setting type is Application/octet-stream will prompt to download
AddType Application/octet-stream. pdf

The htaccess syntax explained above and the usage of Rewritecond and rewriterule in use case analysis, this article will describe in detail the use format of the above two commands, with the variables and rules used. This article is very long Ah, please read carefully, the content is very useful oh.

rewritecond Instruction Format

"description" defines the condition that overrides occur
"Grammar" Rewritecond teststring Condpattern [flags]

The Rewritecond directive defines a rule condition. There may be one or more rewritecond directives in front of a rewriterule instruction, and Rewriterule rewrite rules are applied to the current URL processing only if the Rewritecond condition (Condpattern) matches successfully.

TestString is a plain text string that includes the following variable structure extensions in addition to ordinary characters:

rewritemap Extension: The reference method is: ${mapname:key|default} for details, see the REWRITEMAP directive.

TestString can contain server variables, referenced by:%{name_of_variable}

name_of_variable can be one of the strings listed in the following table:

HTTP Header connection and request Server itself Date and time Other
Http_user_agent Document_root Time_year Api_version
Http_referer Server_admin Time_mon The_request
Http_cookie server_name Time_day Request_uri
http_forwarded Server_addr Time_hour Request_filename
Http_host Server_port Time_min Is_subreq
Http_proxy_connection Server_protocol Time_sec HTTPS
Http_accept Server_software Time_wday
Remote_addr Time
Remote_host
Remote_port
Remote_user
Remote_ident
Request_method
Script_filename
Path_info
Query_string
Auth_type

These variables correspond to similar named HTTP MIME headers, c variables on Apache servers, and struct TM fields in Unix systems, most of which are described in other manuals or CGI specifications. Some of the variables that are unique to mod_rewrite are as follows:

Is_subreq

If the request being processed is a child request, it will contain the string "true", otherwise it is "false". The module may produce a child request in order to parse the attached file in the URI.

Api_version

This is the version of the Apache module API that is in use (internal interface between the server and the module), which is defined in Include/ap_mmn.h. This module API version corresponds to the version of Apache that is in use (for example, this value is 19,990,320:10 in the release version of Apache 1.3.14). In general, it is the developer of the module that is interested in it.

The_request

This is the full HTTP request line sent by the browser (for example: "Get/index.html Http/1.1″"). It does not contain any other header information sent by the browser.

Request_uri

This is the resource requested in the HTTP request line (for example, "/index.html" in the above example).

Request_filename

This is the file path name of the complete local file system that matches the request.

HTTPS

If the connection uses SSL/TLS, it will contain the string "on" or "Off" (the variable can be used safely regardless of whether the mod_ssl has been loaded).

Other precautions:

Script_filename and request_filename contain the same values-that is, the filename field in the REQUEST_REC structure inside the Apache server. The first is the CGI variable name that everyone knows, and the second is a copy of Request_uri (the URI field in the REQUEST_REC structure).

    1. Special form:%{env:variable}, where the variable can be any environment variable. It is obtained by searching the Apache internal structure or (if not found) by the Apache server process through getenv ().
    2. Special form:%{ssl:variable}, where the variable can be the name of an SSL environment variable, regardless of whether the Mod_ssl module is already loaded (empty string when not loaded). For example:%{ssl:ssl_cipher_usekeysize} will be replaced with 128.
    3. Special form:%{http:header}, where the header can be the name of any HTTP MIME header. It can always be obtained by looking up HTTP requests. For example:%{http:proxy-connection} will be replaced with the value of the proxy-connection:http header.
    4. Default form:%{la-u:variable}, the final value of the variable is determined after an internal (URL-based) child request is executed. Use this method when you need to use a variable that is currently unknown but will be set in the subsequent procedure. For example, you need to use%{la-u:remote_user} in order to override the Remote_user variable in a server-level configuration (httpd.conf file). Because this variable is overridden by a URL (mod??). _rewrite) Step after the authentication step is set. On the other hand, because Mod_rewrite is configured with the API remediation steps for the directory-level (. htaccess file), the authentication step is preceded by the API remediation step, so you can use%{remote_user}.
    5. Default form:%{la-f:variable}, the final value of the variable is determined after an internal (file-based) child request is executed. In most cases, the la-u is the same as above.
Condpattern is a conditional pattern, which is a regular expression applied to the current teststring instance. TestString will be calculated first and then matched with Condpattern.

Note: Condpattern is a Perl-compatible regular expression, but there are several additions:

1, can be used at the beginning of the Condpattern string "!" (exclamation point) to specify a mismatch.
2, Condpatterns has a number of special variants. In addition to the standard usage of regular expressions, there are the following uses:

Treats Condpattern as a pure string, compared to teststring by dictionary order. True if TestString is less than Condpattern.
">condpattern" ————-(dictionary order greater than)

Treats Condpattern as a pure string, compared to teststring by dictionary order. True if TestString is greater than condpattern.
"=condpattern" ————-(dictionary order equals)

Treats Condpattern as a pure string, compared to teststring by dictionary order. True if TestString equals Condpattern (two strings are exactly equal by character).

If Condpattern is ""-(two double quotes), then teststring will be compared to an empty string.
"-D" ————-(directory)

Treat TestString as a pathname and test whether it is a directory that exists.
"-F" ————-(regular file)

Treat teststring as a path name 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 a size greater than 0.
"-L" ————-(symbolic Connection)

Treat TestString as a pathname and test whether it is an existing symbolic connection.
"-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" ————-(files that exist on a child request)

Check if teststring is a valid file and can be accessed under the current access control configuration of the server. It uses an internal sub-request to do the check, because it will reduce the performance of the server, so please use it carefully!
"-U" ————-(the URL that exists for a child request)

Check if teststring is a valid URL and can be accessed under the current access control configuration of the server. It uses an internal sub-request to do the check, because it will reduce the performance of the server, so please use it carefully!
Note: All of these tests can be prefixed with an exclamation point ("!") To achieve the reversal of test conditions.

Append a special tag [flags] after condpattern as the third parameter of the Rewritecond directive. Flags is a comma-delimited list of the following tokens:

"Nocase| NC "————— (ignoring case)

It makes the test ignore case, and the expanded teststring and Condpattern ' AZ ' and ' A-Z ' are indistinguishable. This tag is used only for comparisons between TestString and Condpattern, and checks on file systems and child requests do not work.
"Ornext|or" ————— (or Next condition)

Code Shorthand Full Write explain
R[=code] redirect Force external redirection
F Forbidden Disables the URL and returns the 403HTTP status code.
G Gone Force URL to obsolete
P Proxy Force the use of proxy forwarding.
L Last Indicates that the current rule is the last rule, stopping the rewrite of the rule after parsing.
N Next Re-run the rewrite process starting with the first rule.
C chain Associate with Next rule
If the rule match is handled normally, the flag is invalid and if it does not match, all the associated rules below are skipped.
T=mime-type type Force MIME Type
Ns Nosubreq Only for not internal sub-requests
NC nocase Case insensitive
QSA Qsappend Append Request string
NE Noescape Do not escape special characters in output
Pt passthrough Pass to next processing
S=num Skip Skip Num Rule
E=var:val Env Setting environment variables
co=name:val:domain[:lifetime[:p Ath]] Cookies Set cookies

Redirect| R [=code] (Force redirect redirect)

A substitution that is prefixed with http://thishost[:thisport]/(making the new URL a URI) can be forced to perform an external redirect. If code is not specified, an HTTP response code of 302 (temporary move) is generated. If you need to use a different response code in the range of 300-400, you can specify this value here, plus one of the following symbol names: Temp (default), permanent, seeother. It can be used to feedback the normalized URL to the client, such as rewriting "/~" to "/u/", or/u/user plus slashes, etc.

Note: When using this tag, you must ensure that the replacement field is a valid url! Otherwise, it will point to an invalid location! And keep in mind that this tag itself is just a prefix to the URL plus http://thishost[:thisport]/, and the rewrite operation will still continue. In general, you will want to stop the rewrite operation and immediately redirect, then you also need to use the ' L ' tag.

forbidden| F (mandatory URL for forbidden Forbidden)

Forces the current URL to be disabled, that is, immediately feedback an HTTP response code of 403 (forbidden). With this tag, you can link several rewriteconds to conditionally block certain URLs.

gone| G ' (force URL to obsolete gone)

Forces the current URL to be obsolete, that is, immediately feedback an HTTP response code 410 (deprecated). Using this tag, you can indicate that the page has been deprecated and does not exist.

proxy| P (Force agent proxy)

This flag causes the replacement ingredient to be internally coerced to the proxy request and immediately (that is, the rewrite rule handles immediate interrupts) handing over the processing to the proxy module. You must make sure that this replacement string is a valid URI (such as a common one that starts with http://hostname) that can be handled by the Apache proxy module. With this tag, some remote components can be mapped to the local server namespace, thereby enhancing the functionality of the Proxypass directive.

Note: To use this feature, the proxy module must be compiled on the Apache server. If you are not sure, you can check the output of "httpd-l" for mod_proxy.c. If so, mod_rewrite can use this feature, and if not, you must enable Mod_proxy and recompile the HTTPD program.

Last| L (last Rule)

Stops the rewrite operation immediately and no longer applies another rewrite rule. It corresponds to the last command in Perl or the break command in the C language. This tag prevents the currently overridden URL from being overridden by its successor rule. For example, use it to rewrite the URL of the root path ('/') to a URL that actually exists, for example, '/e/www/'.

Next| N (re-execute next round)

Re-executes the rewrite operation (starting with the first rule). The URL that was processed again is not the original URL, but the URL that was processed by the last rewrite rule. It corresponds to the next command in Perl or the Continue command in the C language. This tag can restart the rewrite operation, that is, immediately return to the head of the loop.
But be careful not to create a dead loop!

chain| C (link to next rule chained)

This tag causes the current rule to be linked to the next rule (which itself can be linked to its successor rule and can be so repeated). It produces such an effect: if a rule is matched, it will usually continue to process its successor, that is, the tag does not work, and if the rule cannot be matched, then its subsequent linked rules are ignored. For example, when performing an external redirect, for a directory-level rule set, you may need to delete ". www" (where ". www" should not appear).

type| T=mime-type (force MIME type types)

The mandatory MIME type for the target file is Mime-type. For example, it can be used to simulate the Scriptalias directive in Mod_alias to internally force the MIME type of all files in the mapped directory to be "application/x-httpd-cgi".

nosubreq| NS (only for no internal sub-request processing no internal sub-request)

This token forces the rewrite engine to skip the rewrite rule when the current request is an internal child request. For example, when Mod_include tries to search for possible directory default files (index.xxx), Apache generates child requests internally. A child request, which is not necessarily useful, and may even throw an error if the entire ruleset is working. Therefore, you can use this tag to exclude certain rules.

Follow these guidelines according to your needs: If you use URL prefixes with CGI scripts to force them to be handled by CGI scripts, the error rate (or overhead) of processing a child request is high, in which case you can use this tag.

nocase| NC (ignoring casing no case)

It makes the pattern ignore case, that is, ' A-Z ' and ' A-Z ' are not different when pattern matches the current URL.

qsappend| QSA (Append request string query string append)

This flag forces the rewrite engine to append a request string to an existing replacement string, rather than a simple replacement. You can use this tag if you need to add information to the request string through a rewrite rule.

Noescape|ne (do not escape URI in output no URI escaping)

This flag prevents Mod_rewrite from applying a general URI escape rule to the overridden result. In general, special characters (such as '% ', ' $ ', '; ') And so on) will be escaped to the equivalent hexadecimal encoding. This tag prevents such escapes from allowing symbols such as percent signs to appear in the output, such as:

The rewriterule/foo/(. *)/bar?arg=p1\=$1 [R,ne] can turn '/foo/zed ' to a secure request '/bar?arg=p1=zed '.

Passthrough|pt (hand over to the next processor pass through)

This flag forces the rewrite engine to set the URI field in the internal structure Request_rec to the value of the FileName field, which is only a small modification to the Alias,scriptalias from other URIs to the file name translator Redirect The output of the command is subsequently processed. Give an example of what it means: if you want to rewrite/ABC as/def through the mod_rewrite rewrite engine, and then convert/def to/ghi by Mod_alias, you can:

Rewriterule ^/abc (. *)/def$1 [Pt]alias/def/ghi

If the PT tag is omitted, although mod_rewrite works fine, that is, as a URI to the file name translator using the API, it can rewrite uri=/abc/... For filename=/def/..., however, subsequent mod_alias are invalidated when attempting to translate the URI to the file name.

Note: You must use this tag if you need to mix a different module that contains a URI to the file name translator. Mixed use of Mod_alias and mod_rewrite is a typical example.

For Apache hackers

If the current Apache API in addition to the URI to the file name hook, there is a file name to the file name of the hook, you do not need this tag! However, if there is no such a hook, then this tag is the only solution. Apache Group has discussed this issue and will add such a hook in Apache version 2.0.

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

This flag forces the rewrite engine to skip the NUM rules succeeding the current matching rule. It can implement a pseudo-If-then-else construct: The last rule is the then clause, and the skip=n rule that is skipped is the ELSE clause. (IT and ' chain| The C ' tag is different!)

env| E=var:val (SET environment variable environment variable)

This flag causes the value of the environment variable VAR to be Val, and Val can contain an extensible inverse reference to the regular expression $n and%n. This tag can be used multiple times to set multiple variables. These variables can be referenced indirectly in many subsequent cases, but usually in Xssi (via) or CGI (e.g. $ENV {' VAR '}), or by%{env:var} in the pattern of subsequent rewritecond instructions. Use it to peel and remember some information from the URL.

cookie|co=name:val:domain[:lifetime[:p Ath]] (set cookies)

It sets a cookie on the client browser. The name of the cookie is "name" and its value is Val. The Domain field is the field of the cookie, such as '. Apache.org ', the optional lifetime is the number of minutes of the cookie's lifetime, and the optional path is the cookie.

Examples of Rewritecond command rules

Rewritecond%{remote_host} ^andelse.com [OR]
Rewritecond%{remote_host} ^*.andelse.com
Rewriterule ... Rule set for these 2 hosts

Rewritecond% {http_user_agent} ^mozilla.*
Rewriterule ^/$/homepage. Max. html [L]
If you use the browser recognition logo as ' Mozilla ', then you will get the content to maximize the homepage homepage. Max. HTML (contains frames, etc.).

Rewriterule instruction Format

"description" defines the rules for overriding
"Grammar" Rewriterule Pattern Rewritepattern [flags]

Rewriterule directives, you can define a rewrite rule, and the order between rules is important. For Apache1.2 and later versions, the template (pattern) is a POSIX regular that matches the current URL. The current URL is not necessarily the URL that was originally submitted, because the URL might have been processed by some rules before this rule. Rewritepattern Most of the articles are written as substitution, which is written as rewritepattern for a clearer understanding.

Pattern can use the following special matching rules, such as PHP, and other language similar.

"." ——————-all characters except line breaks
"\w" —————-match letters or numbers or underscores or kanji
"\s" ————— – matches any whitespace character
"\d" ————— – Match numbers
"\b" ————— – matches the beginning or end of a word
"^" —————— start of matching string
"$" —————— the end of the matching string
"*" —————— repeat 0 or more times
"+" —————— repeat one or more times
"?" ——————-repeat 0 or one time
' {n} ' —————-repeat n times
"{N,}" ————— repeated n or more times
' {n,m} ' ————-repeat N to M times
"[0-9]" ———— – matches a single number

The Rewritepattern is a rewritepattern-defined replacement for the URL after the pattern match. When the application is replaced, the previous pattern matches the first () Rewritepattern can be quoted, and the second () matches in the app ... And so on

Append a special tag [flags] after rewritepattern as the third parameter of the Rewriterule directive. Flags can be used in the same way as the rewritecond used above. Illustrate Rewriterule syntax

Rewriterule index.html index.php

For example: http://www.andelse.cn/index.html-http://www.andelse.cn/index.php

Rewriterule ^test ([0-9]*). html$ test.php?id=$1

For example: http://www.andelse.cn/test8.html-http://www.andelse.cn/test.php?id=8

Rewriterule ^cat-([0-9]+)-([0-9]+) \.html$ cat.php?id1=$1&id2=$2

For example: http://www.andelse.cn/cat-1-3.html-http://www.andelse.cn/cat.php?id1=1&id2=3

Rewriterule ^cat-([a-za-z0-9\-]*)-([0-9]+)-([0-9]+] \.html$ cat.php?id0=$1&id1=$2&id2=$3

For example: http://www.andelse.cn/cat-zbc2ac-3-5.html-http://www.andelse.cn/cat.php?id0=zbc2ac&id1=3&id2=5

Rewriterule ^cat1-([0-9]+)-([0-9]+)-([0-9]+] \.html$ cat1.php?id1=$1&id2=$2&id3=$3

For example: http://www.andelse.cn/cat1-4-3-8.html-http://www.andelse.cn/cat1.php?id1=4&id2=3&id3=8

Rewriterule ^cat ([0-9]*)/$ cat.php?id1=$1

For example: http://www.andelse.cn/cat5/-http://www.andelse.cn/cat.php?id1=5

Rewriterule ^CATM ([0-9]*)/([0-9]*)/$ catm.php?id1=$1&id2=$2

For example: http://www.andelse.cn/catm6/3/-http://www.andelse.cn/catm.php?id1=6&id2=3

. htaccess syntax and application

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.