Today's support content needs to test Apache page redirection. Simply put, Apache is configured to automatically convert the old URL address into a new URL output.
- First, the Apache redirection function needs to call the mod_rewrite module. Because the module is included in the modules folder of apache2.2, we only need to enable HTTP. loadmodule rewrite_module modules/mod_rewrite.so In the conf file (remove the '#' above ).
Apache module mod_rewrite description
Note: |
Provides a rule-based engine for real-time redirection to URL requests. |
Status: |
Extension |
Module name: |
Rewrite_module |
Source file: |
Mod_rewrite.c |
Compatibility: |
Included in Apache 1.3 and its latest version |
- Modify the HTTP. conf file and append the following code:
# Enable rewrite Module
Rewriteengine on
# Set the log output position ()
Rewritelog "F:/local/apache2.2/logs/Rewrite. log"
# Example: replacing page. jsp? Id = 30800 is the new address http: // localhost/WebAdmin/index. jsp
Rewritecond % {QUERY_STRING} ^ id = 30800 $
Rewriterule ^/page. jsp $ http: // localhost/WebAdmin/index. jsp [l]
Common commands:
Syntax: rewritebaseURL-Path
The rewritebase command explicitly sets the baseline URL for directory-level rewriting. The default value is,RewriteBase
Physical-directory-PathWhen replacing a new URL, this module must inject the URL into the server again. Therefore, it must know the corresponding URL prefix or URL benchmark. Generally, this prefix is the corresponding file path.However, most website URLs do not directly correspond to their physical file paths, so this assumption is generally not acceptable!In this case, you must useRewriteBase
Command to specify the correct URL prefix.
Rewriteengine on
# Let the server know that we were reached via/XYZ and not
# Via the physical path prefix/ABC/DEF
Rewritebase/XYZ
Syntax: rewritecondTeststring Condpattern
RewriteCond
The command defines a rule condition, that is, inRewriteRule
One or more commandsRewriteCond
Command. The rewriting rule after the condition only matches the current Uri and pattern.AndIt works only when these conditions are met.
TeststringIs a plain text string, but can contain the following extensible components.CondpatternIs conditional pattern,That is, One is applied to the current instanceTeststringRegular Expression,That is,TeststringIt will be calculated and thenCondpatternMatch.
Rewritecond % {http_user_agent} ^ Mozilla .*
Rewriterule ^/$/homepage.max.html [l]
Rewritecond % {http_user_agent} ^ lynx .*
Rewriterule ^/$/homepage.min.html [l]
Rewriterule ^/$/homepage.std.html [l]
Syntax: rewriteengine on | off
RewriteEngine
Command to enable or disable the rewrite engine at runtime. If it is setoff
This module does not perform any rewrite operation at the runtime, or even updateSCRIPT_URx
Environment variable. Using this command can invalidate this module without commenting on allRewriteRule
Command!
Note: by default, rewrite configurations cannot be inherited, that is, you must setRewriteEngine on
Command.
Syntax: rewritelogFile-Path
RewriteLog
Specifies the name of the file used to record all rewrite operations. If the file name is not a slash ('/
'), It is relativeServer Root. This command should only appear in server-level configuration.
If you want to disable the record for the rewrite operation, we do not recommend
FilenameSet
/dev/null
Because, although the rewrite engine cannot output records, this log file will still be created internally,
This reduces the server speed and does not help administrators!To disable logs, you can delete or annotate them.
RewriteLog
Command, or use
RewriteLogLevel 0
! Rewritelog "/usr/local/var/Apache/logs/Rewrite. log"
Syntax: rewriteloglevelLevel
RewriteLogLevel
Command to set the level of detail of the rewrite engine log. The default value 0 indicates that no operation is recorded, and the value 9 or greater indicates that all operations are recorded.
To disable rewrite engine logs, you can set this value to 0 to close all rewrite Operation Records. High usageLevelThe value will cause a sharp decrease in the Apache server speed! Rewrite logs with a value greater than 2LevelThe value is only used for debugging!
Rewriteloglevel 3
Syntax: rewriterulePattern Substitution
RewriteRule
Commands are the basis of the rewrite engine. This command can be used multiple times. Each instruction defines a simple rewrite rule. TheDefine orderEspeciallyImportantBecause the rules take effect one by one at the runtime.
PatternIs a regular expression compatible with Perl that acts on the current URL. Here, ''current ''refers to the value of the URL when the rule takes effect. It may be different from the requested URL, because other rules may have been matched before and modified.
[Flags]
- '
redirect|R
[=Code]'(Force redirectREdirect)
Tohttp://thishost[:thisport]/
(Make the new URL a URI)SubstitutionYou can forcibly execute an external redirection. IfCodeIf this parameter is not specified, an HTTP response code 302 (temporary movement) is generated ). To use other response codes within the range of-, you only need to specify this value here. In addition, you can also use one of the following symbol names:temp
(Default ),permanent
,seeother
. It can be used to feed the canonicalized URL back to the client,For example, Override''/~
''Is''/u/
'', Or/u/
UserAdd a slash, and so on.Note:When using this tag, make sure that this field is a valid URL! Otherwise, it will point to an invalid location! Remember that this tag only addshttp://thishost[:thisport]/
. In general, if you want to stop the rewrite operation and redirect immediately, you also need to use the 'l' flag.
- '
forbidden|F
'(Force the URL to be disabledFOrbidden)
Force the current URL to be disabled,That is, Immediately feedback an HTTP response code 403 (Forbidden ). With this tag, you can link several rewriteconds to block some URLs with conditions.
- '
gone|G
'(Force the URL to be obsoleteGOne)
Force 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 deprecated and does not exist.
- '
proxy|P
'(Force proxyPRoxy)
This flag forces the replacement component internally as a proxy request and immediately (That is, Rewrite rule processing is interrupted immediately) hand over the processing to the proxy module. You must make sure that this replacement string is valid (For exampleCommon http://
HostnameThe URI that can be processed by the Apache proxy module. Using this tag, you can map some remote components to the local server namespace, thus enhancing the proxypass command function.Note: To use this function, the proxy module must be compiled on the Apache server. If you are not sure, check''httpd -l
''Output?mod_proxy.c
. If yes, mod_rewrite can use this function. If not, you must enable mod_proxy and recompile''httpd
''Program.
- '
last|L
'(Last ruleLAST)
Stop the rewrite operation immediately and no other rewrite rules will be applied. It correspondslast
In command or C Languagebreak
Command. This mark can prevent the URL that has been rewritten from being overwritten by its subsequent rules. For example, you can use it to override the URL of the root path ('/
') Is the actual URL,For example,'/e/www/
'.
- '
next|N
'(Re-ExecuteNEXT round)
Re-execute the rewrite operation (starting from the first rule again). At this time, the URL processed again is not the original URL, but the URL processed by the last rewrite rule. It correspondsnext
In command or C Languagecontinue
Command. This flag allows you to re-start the rewrite operation,That isImmediately return to the loop header.
But be careful not to create an endless loop!
- '
chain|C
'(Linked to the next ruleCHained)
This flag enables the current rule to be connected to the next rule (it can be linked to its successor rule itself,And can be so repeated) The rules are linked. It produces the following effect: if a rule is matched, it will usually continue to process its successor rules,That is, This tag does not work; if the ruleNoThe rules for subsequent links are ignored. For example, when executing an external redirection, you may need to delete ''from a directory-level rule set''.www
''(This should not contain''.www
).
- '
type|T
=Mime-type'(Mandatory MIME typeTYpe)
The MIME type of the target file is mandatoryMime-type. For example, it can be used to simulatemod_alias
InScriptAlias
Command to force the MIME type of all files in the mapped directory''application/x-httpd-cgi
''.
- '
nosubreq|NS
'(Only used to process internal sub-RequestsNO internalSUB-request)
When the current request is an internal subrequest, this flag forces the rewrite engine to skip this rewrite rule. For examplemod_include
Try to search for possible default directory files (index.xxx
), Apache will request internally. It is not necessarily useful for subrequests. If the entire rule set works, it may even cause errors. Therefore, you can use this tag to exclude certain rules.Follow the following principles as needed: if you use a URL prefix with CGI scripts to force them to be processed by CGI scripts, the error rate (or overhead) of sub-requests is high, in this case, you can use this tag.
- '
nocase|NC
'(Case insensitiveNOCASE)
It enablesPatternCase Insensitive,That is, InPatternWhen matching with the current URL, there is no difference between 'a-Z' and 'a-Z.
- '
qsappend|QSA
'(Append request stringQUerySTringAPpend)
This flag forces the rewrite engine to append a request 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.
- '
noescape|NE
'(Do not escape the URI in the outputNO URIEScaping)
This flag prevents mod_rewrite from applying regular URI escape rules to rewrite results. Generally, special characters (such as '%', '$', ';') are escaped as hexadecimal encoded values. 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/%3d$1 [R,NE]
Enable'/foo/zed
'Redirect to a secure request'/bar?arg=P1=zed
'.
- '
passthrough|PT
'(Hand over to the next ProcessorPAssTHrough)
This flag forces the rewrite engine to change the internal structurerequest_rec
Inuri
Set the fieldfilename
Field value, which is only a small modification, so that it canAlias
,ScriptAlias
,Redirect
And so onCommand output for subsequent processing. For examplemod_rewrite
Rewrite Engine/abc
Is/def
And thenmod_alias
Enable/def
To/ghi
, You can do this:RewriteRule ^/abc(.*) /def$1 [PT]
Alias /def /ghi
If this parameter is omittedPT
Mark, althoughmod_rewrite
Normal operation,That isAs a file name translator using the API Uri, it can be rewrittenuri=/abc/...
Isfilename=/def/...
Howevermod_alias
When attempting to translate a URI to a file name, it will become invalid.
Note:If you want to mix different modules that contain URIs to the file name translator, you must use this tag.. Hybrid usemod_alias
Andmod_rewrite
Is a typical example.
For Apache hackersIf there is a hook from the URI to the file name in Apache API besides the hook from the URI to the file name, you do not need to mark it! However, if there is no such hook, this tag is the only solution. Apache Group discussed this issue and added such a hook in Apache 2.0.
- '
skip|S
=Num'(Skip subsequent rulesSKIP)
This flag forces the rewrite engine to skip the nextNumRules. It can implement the construction of a pseudo if-then-Else: the last rule is the then clause, and is skippedskip=N
The rule is the else clause. (It and 'chain | C' mark isDifferentOf !)
- '
env|E=
VaR:Val'(Set Environment VariablesENvironment variable)
This flag makes the environment variableVaRIsVal,ValIt can contain scalable 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, but usually in xssi (<!--#echo var="VAR"-->
) Or CGI (For example $ENV{'VAR'}
In the pattern of the subsequent rewritecond command.%{ENV:VAR}
For reference. You can use it to strip from the URL and remember some information.
- '
cookie|CO=
Name:Val:Domain[:Lifetime[:Path] '(SetCOOkie)
It sets a cookie on the client browser. The cookie name isNameThe value isVal.DomainThe field is the Cookie's domain, such as '.apache.org'. Optional.LifetimeIs the number of minutes in the life cycle of a cookie. Optional.PathIs the Cookie Path.