<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L] </IfModule> <FilesMatch "^parser_\d+.js$"> SetHandler php5-script </FilesMatch> <FilesMatch "^parser.js$"> SetHandler php5-script </FilesMatch>
说明 | 封装指令并根据指定的模块是否启用为条件而决定是否进行处理 |
---|---|
语法 | <IfModule [!]module-file|module-identifier> ... </IfModule> |
作用域 | server config, virtual host, directory, .htaccess |
覆盖项 | All |
状态 | 核心(C) |
模块 | core |
兼容性 | module-identifier仅在 Apache 2.1 及以后的版本中可用 |
<IfModule test>...</IfModule>
配置段用于封装根据指定的模块是否启用而决定是否生效的指令。在<IfModule>
配置段中的指令仅当test为真的时候才进行处理。如果test为假,所有其间的指令都将被忽略。
<IfModule>
段中的test可以为以下两种方式之一:
在第一种情况下,起始和结束标记之间的指令仅当module被载入后才被执行。此模块可以为编译时静态链接进核心的模块或是使用LoadModule
指令动态载入的模块。第二种情况则相反,仅当module没有载入时才进行指令的处理。
module可以是模块的标识符或者是编译模块时的文件名。比如,rewrite_module
就是一个模块标识符,而mod_rewrite.c
则是编译模块时的文件名。如果模块包含多个源代码文件,您应当使用包含STANDARD20_MODULE_STUFF
字符串的那个。
<IfModule>
配置段是可以嵌套的,从而可以实现简单的多模块测试。
<IfModule>
配置段中。
说明 | Enables or disables runtime rewriting engine |
---|---|
语法 | RewriteEngine on|off |
默认值 | RewriteEngine off |
作用域 | server config, virtual host, directory, .htaccess |
覆盖项 | FileInfo |
状态 | 扩展(E) |
模块 | mod_rewrite |
RewriteEngine
directive enables or disables the runtime rewriting engine. If it is set tooff
this module does no runtime processing at all. It does not even update theSCRIPT_URx
environment variables.
Use this directive to disable the module instead of commenting out all the RewriteRule
directives!
Note that, by default, rewrite configurations are not inherited. This means that you need to have aRewriteEngine on
directive for each virtual host in which you wish to use it.
说明 | Defines rules for the rewriting engine |
---|---|
语法 | RewriteRule Pattern Substitution |
作用域 | server config, virtual host, directory, .htaccess |
覆盖项 | FileInfo |
状态 | 扩展(E) |
模块 | mod_rewrite |
兼容性 | The cookie-flag is available in Apache 2.0.40 及以后的版本中可用 |
RewriteRule
directive is the real rewriting workhorse. The directive can occur more than once. Each directive then defines one single rewriting rule. Thedefinition order of these rules is important, because this order is used when applying the rules at run-time.
Pattern is a perl compatible regular expression which gets applied to the current URL. Here "current" means the value of the URL when this rule gets applied. This may not be the originally requested URL, because any number of rules may already have matched and made alterations to it.
Some hints about the syntax of regular expressions:
Text:.
Any single character[
chars]
Character class: One of chars[^
chars]
Character class: None of chars text1|
text2 Alternative: text1 or text2 Quantifiers:?
0 or 1 of the preceding text*
0 or N of the preceding text (N > 0)+
1 or N of the preceding text (N > 1) Grouping:(
text)
Grouping of text (either to set the borders of an alternative or for making backreferences where the Nth group can be used on the RHS of a RewriteRule with$
N) Anchors:^
Start of line anchor$
End of line anchor Escaping:\
char escape that particular char (for instance to specify the chars ".[]()
" etc.)
For more information about regular expressions have a look at the perl regular expression manpage ("perldoc perlre"). If you are interested in more detailed information about regular expressions and their variants (POSIX regex etc.) have a look at the following dedicated book on this topic:
Mastering Regular Expressions, 2nd Edition
Jeffrey E.F. Friedl
O'Reilly & Associates, Inc. 2002
ISBN 0-596-00289-0
Additionally in mod_rewrite the NOT character ('!
') is a possible pattern prefix. This gives you the ability to negate a pattern; to say, for instance: "if the current URL doesNOT match this pattern". This can be used for exceptional cases, where it is easier to match the negative pattern, or as a last default rule.
$N
in the substitution string!
Substitution of a rewriting rule is the string which is substituted for (or replaces) the original URL for whichPattern matched. Beside plain text you can use
$N
to the RewriteRule pattern%N
to the last matched RewriteCond pattern%{VARNAME}
)${mapname:key|default}
)Back-references are $
N (N=0..9) identifiers which will be replaced by the contents of theNth group of the matched Pattern. The server-variables are the same as for theTestString of a RewriteCond
directive. The mapping-functions come from theRewriteMap
directive and are explained there. These three types of variables are expanded in the order of the above list.
As already mentioned above, all the rewriting rules are applied to the Substitution (in the order of definition in the config file). The URL iscompletely replaced by the Substitution and the rewriting process goes on until there are no more rules unless explicitly terminated by aL
flag - see below.
There is a special substitution string named '-
' which means: NO substitution! Sounds silly? No, it is useful to provide rewriting rules whichonly match some URLs but do no substitution, 例如,in conjunction with theC (chain) flag to be able to have more than one pattern to be applied before a substitution occurs.
Pattern will not match against the query string. Instead, you must use aRewriteCond
with the%{QUERY_STRING}
variable. You can, however, create URLs in the substitution string containing a query string part. Just use a question mark inside the substitution string to indicate that the following stuff should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just the question mark. To combine a new query string with an old one, use the[QSA]
flag (see below).
There is a special feature: When you prefix a substitution field with http://
thishost[:thisport] thenmod_rewrite automatically strips it out. This auto-reduction on implicit external redirect URLs is a useful and important feature when used in combination with a mapping-function which generates the hostname part. Have a look at the first example in the example section below to understand this.
Remember: An unconditional external redirect to your own server will not work with the prefixhttp://thishost
because of this feature. To achieve such a self-redirect, you have to use theR-flag (see below).
Additionally you can set special flags forSubstitution by appending
[
flags]
as the third argument to the RewriteRule
directive. Flags is a comma-separated list of the following flags:
chain|C
' (chained with next rule).www
" part inside a per-directory rule set when you let an external redirect happen (where the ".www
" part should not to occur!).cookie|CO=
NAME:VAL:domain[:lifetime[:path]]' (setcookie)env|E=
VAR:VAL' (set environment variable)$N
和%N
which will be expanded. You can use this flag more than once to set more than one variable. The variables can be later dereferenced in many situations, but usually from within XSSI (via <!--#echo var="VAR"-->
) or CGI (例如, $ENV{'VAR'}
). Additionally you can dereference it in a following RewriteCond pattern via%{ENV:VAR}
. Use this to strip but remember information from URLs.forbidden|F
' (force URL to be forbidden)gone|G
' (force URL to be gone)handler|H
=Content-handler' (force Contenthandler)mod_alias
directive ScriptAlias
which internally forces all files inside the mapped directory to have a handler of "cgi-script
".last|L
' (last rule)last
command or the break
command from the C language. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules. For example, use it to rewrite the root-path URL ('/
') to a real one, 例如,'/e/www/
'.next|N
' (next round)next
command or the continue
command from the C language. Use this flag to restart the rewriting process,i.e., to immediately go to the top of the loop.nocase|NC
' (no case)noescape|NE
' (no URI escaping of output)RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]
/foo/zed
' into a safe request for '/bar?arg=P1=zed
'.nosubreq|NS
' (used only if no internalsub-request)mod_include
tries to find out information about possible directory default files (index.xxx
). On sub-requests it is not always useful and even sometimes causes a failure to if the complete set of rules are applied. Use this flag to exclude some rules.Use the following rule for your decision: whenever you prefix some URLs with CGI-scripts to force them to be processed by the CGI-script, the chance is high that you will run into problems (or even overhead) on sub-requests. In these cases, use this flag.
proxy|P
' (force proxy)http://
hostname) which can be handled by the Apache proxy module. If not you get an error from the proxy module. Use this flag to achieve a more powerful implementation of theProxyPass directive, to map some remote stuff into the namespace of the local server. 注意:mod_proxy
must be enabled in order to use this flag.
passthrough|PT
' (pass through to next handler)uri
field of the internalrequest_rec
structure to the value of the filename
field. This flag is just a hack to be able to post-process the output ofRewriteRule
directives by Alias
, ScriptAlias
,Redirect
, etc. directives from other URI-to-filename translators. A trivial example to show the semantics: If you want to rewrite/abc
to /def
via the rewriting engine of mod_rewrite
and then/def
to /ghi
with mod_alias
:
RewriteRule ^/abc(.*) /def$1 [PT]
Alias /def /ghi
PT
flag then mod_rewrite
will do its job fine,i.e., it rewrites uri=/abc/...
to filename=/def/...
as a full API-compliant URI-to-filename translator should do. Thenmod_alias
comes and tries to do a URI-to-filename transition which will not work. Note: You have to use this flag if you want to intermix directives of different modules which contain URL-to-filename translators. The typical example is the use ofmod_alias
和mod_rewrite
..
qsappend|QSA
' (query string append)redirect|R
[=code]' (force redirect)http://thishost[:thisport]/
(which makes the new URL a URI) to force a external redirection. If nocode is given a HTTP response of 302 (MOVED TEMPORARILY) is used. If you want to use other response codes in the range 300-400 just specify them as a number or use one of the following symbolic names:temp
(default), permanent
, seeother
. Use it for rules which should canonicalize the URL and give it back to the client, 例如,translate "/~
" into "/u/
" or always append a slash to/u/
user, etc.Note: When you use this flag, make sure that the substitution field is a valid URL! If not, you are redirecting to an invalid location! And remember that this flag itself only prefixes the URL withhttp://thishost[:thisport]/
, rewriting continues. Usually you also want to stop and do the redirection immediately. To stop the rewriting you also have to provide the 'L' flag.
skip|S
=num' (skip next rule(s))skip=N
where N is the number of rules in the else-clause. (This is not the same as the 'chain|C' flag!)type|T
=MIME-type' (force MIME type).php
files to be displayed by mod_php
if they are called with the.phps
extension:
RewriteRule ^(.+\.php)s$ $1 [T=application/x-httpd-php-source]
There is one exception: If a substitution string starts with "http://
" then the directory prefix willnot be added and an external redirect or proxy throughput (if flagP is used!) is forced!
RewriteEngine On
" in these files
和 "
Options FollowSymLinks
" must be enabled. If your administrator has disabled override of
FollowSymLinks
for a user's directory, then you cannot use the rewriting engine. This restriction is needed for security reasons.
Here are all possible substitution combinations and their meanings:
Inside per-server configuration (httpd.conf
)
for request "GET /somepath/pathinfo
":
Given Rule Resulting Substitution ---------------------------------------------- ---------------------------------- ^/somepath(.*) otherpath$1 not supported, because invalid! ^/somepath(.*) otherpath$1 [R] not supported, because invalid! ^/somepath(.*) otherpath$1 [P] not supported, because invalid! ---------------------------------------------- ---------------------------------- ^/somepath(.*) /otherpath$1 /otherpath/pathinfo ^/somepath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^/somepath(.*) /otherpath$1 [P] not supported, because silly! ---------------------------------------------- ---------------------------------- ^/somepath(.*) http://thishost/otherpath$1 /otherpath/pathinfo ^/somepath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^/somepath(.*) http://thishost/otherpath$1 [P] not supported, because silly! ---------------------------------------------- ---------------------------------- ^/somepath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo via external redirection ^/somepath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo via external redirection (the [R] flag is redundant) ^/somepath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo via internal proxy
Inside per-directory configuration for /somepath
(i.e., file .htaccess
in dir /physical/path/to/somepath
containingRewriteBase /somepath
)
for request "GET /somepath/localpath/pathinfo
":
Given Rule Resulting Substitution ---------------------------------------------- ---------------------------------- ^localpath(.*) otherpath$1 /somepath/otherpath/pathinfo ^localpath(.*) otherpath$1 [R] http://thishost/somepath/otherpath/pathinfo via external redirection ^localpath(.*) otherpath$1 [P] not supported, because silly! ---------------------------------------------- ---------------------------------- ^localpath(.*) /otherpath$1 /otherpath/pathinfo ^localpath(.*) /otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^localpath(.*) /otherpath$1 [P] not supported, because silly! ---------------------------------------------- ---------------------------------- ^localpath(.*) http://thishost/otherpath$1 /otherpath/pathinfo ^localpath(.*) http://thishost/otherpath$1 [R] http://thishost/otherpath/pathinfo via external redirection ^localpath(.*) http://thishost/otherpath$1 [P] not supported, because silly! ---------------------------------------------- ---------------------------------- ^localpath(.*) http://otherhost/otherpath$1 http://otherhost/otherpath/pathinfo via external redirection ^localpath(.*) http://otherhost/otherpath$1 [R] http://otherhost/otherpath/pathinfo via external redirection (the [R] flag is redundant) ^localpath(.*) http://otherhost/otherpath$1 [P] http://otherhost/otherpath/pathinfo via internal proxy
Example:
We want to rewrite URLs of the form
/
Language /~
Realname/.../
File
into
/u/
Username /.../
File.
Language
We take the rewrite mapfile from above and save it under /path/to/file/map.txt
. Then we only have to add the following lines to the Apache server configuration file:
RewriteLog /path/to/file/rewrite.log RewriteMap real-to-user txt:/path/to/file/map.txt RewriteRule ^/([^/]+)/~([^/]+)/(.*)$ /u/${real-to-user:$2|nobody}/$3.$1
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] # Adds AUTH support to Rest Plugin: RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last] </IfModule>
%{REQUEST_FILENAME} !-d //非目录
%{REQUEST_FILENAME} !-f //非特定文件
满足这个条件的URL进入index.php,否则在webroot的目录,文件都可以在网页中显示出来。