Using. htaccess to implement Apache URL redirection

Source: Internet
Author: User
Tags http redirect password protection

First, what is URL redirection?

URL redirection (URL redirection, or Web address redirection or domain name forwarding) refers to the technology that directs a user to another URL when he or she browses a URL.

Two, URL redirection how to configure?

1) first require Apache to turn on redirection and modify the httpd.conf configuration:

1    Find:2   3 allowoverride None 5 6     7 allowoverride All

2) Remove the following comment

LoadModule rewrite_module modules/mod_rewrite.so      //Remove the line before the #

3) where is the redirect configuration written?

There are two ways, the first is to write in httpd.conf, this kind of writing for the server full permissions of the webmaster, the wording is probably as follows:

<*:80>    ServerAdmin [email protected]    DocumentRoot "/websites/ www "    ServerName localhost    rewriteengine on    rewriterule ^index\.html$ index.php [L]</ VirtualHost >
httpd.conf Configuring URL redirection

4) Here we mainly introduce another way: in the Site directory to use. htaccess, this method is suitable for Web site administrators in the form of virtual host,

The redirection rules set by both approaches are essentially the same, except where the settings are different.

Three, the basic regular expression

Because regular expressions are used extensively in the URL redirection syntax, and regular is something that is not necessarily forgotten every once in a while, it is necessary to review the basic regular notation first:

.    All characters other than line breaks \w match   letters or numbers or underscores or kanji \s   match any white space character \d   match number \b Match   the beginning or end of a word  ^   match string Start  $   Match string End  *   repeat 0 or more times  +   repeat one or more times  ?   Repeats 0 or more times {n}         repeats n times {n,}         repeats n        to M times {n,m}  ()    a parenthesis represents a grouping, the first parenthesis matches the contents of the reference, the second bracket matches the content in the $ $ reference, and so on ...
Iv.. What can htaccess do?

. htaccess files can do things, including: folder password protection, user-defined redirection, custom 404 page, extension pseudo-static, prohibit a specific IP address of the user, only allow specific IP address of the user, prohibit directory list, and so on.

V.. htaccess Grammar Rules

Let's look at an example of an image anti-theft chain:

1 Rewriteengine on
2 Rewitebase/
Rewritecond%{http_referer}!^http://(. +.)? baidu.com/[NC]        //If the source URL is not *.baidu.com

3 Rewritecond%{http_referer}!^$ //and source URL is not empty

4 rewriterule. *. (jpe?g|gif|bmp|png) $/images/nohotlink.jpg [L] //If the file suffix that is accessed is a picture of jpeg,jpg,gif,bmp,png, then redirect to a fixed picture

Then we follow this example to expand the description:

First line:

Rewriteengine on| The Off           //rewriteengine is used to turn on or deactivate the rewrite function.

Second line:

Rewritebase url-Path/* sets the base directory, for example, if you want to rewrtie a file under the root directory, the "/" Rewritebase is used to set the base URL of the override.
When a new URL is replaced, the module must re-inject the URL into the server processing. To do this, it must know its corresponding URL prefix or a URL reference.
Typically, this prefix is the corresponding file path. However, most web site URLs do not correspond directly to their physical file paths, and therefore are not generally allowed to do so! So in this case,
You must use the Rewritebase directive to specify the correct URL prefix. If your site server URL does not correspond directly to the physical file path and you need to use the Rewritebase directive, you must specify Rewriterule in each of the corresponding. htaccess files. */

Third line:

rewritecond teststring Condpattern [flags] /* 1, Rewritecond:

is a plain text string, but can also contain the following extensible components: 3, Rewriterule Reverse reference:
The reference method is $N
The reference method is%N

The reference method is%{name_of_variable} This is the function we use most often
7, Condpattern:
is the conditional pattern, that is, a regular expression applied to the current instance teststring, that is, teststring will be computed and then matched with Condpattern.
Can be used in the pattern string! character (exclamation point) to achieve a matching reversal.
8. See table below
*/
Server variable name_of_variable specific values are shown in the following table:
Http_user_agent//primarily used to detect visitor systems and browsers, etc.Http_referer//which page to link fromHttp_cookiehttp_forwardedhttp_host//Domain namehttp_proxy_connectionhttp_accept Remote_addrremote_hostremote_userremote_identrequest_methodscrip T_filenamepath_infoquery_stringauth_typedocument_rootserver_adminserver_nameserver_addrserver_portserver_ Protocolserver_softwaretime_yeartime_montime_daytime_hourtime_mintime_sectime_wday Timeapi_version //This is the version of the Apache module API in use in httpd (internal interface between server and module), which is defined in Include/ap_mmn.h. This version of the module corresponds to the version of Apache being used (for example, in the release version of Apache 1.3.14, this value is 19,990,320:10). In general, it is the author of the module that is interested in it. the_request //This is the complete HTTP request line sent by the browser to the server. (For example, "get/index.html Http/1.1″"). It does not contain any additional header information sent by the browser. Request_uri //This is the resource requested in the HTTP request line. request_filename //This is the file path name or description of the complete local file system that matches the request. Is_subreq //If the request being processed is a child request, it contains the string "true", otherwise it is "false". module in order to parse additional files in the URI, it is possible to generate a child request. 

Flags

rewriterule Flag
Rewriterule Mark Meaning Description
R Redirect Issue an HTTP redirect
F Forbidden Disallow access to URL addresses
G Gone Tag URL address does not exist
P Proxy Pass the URL address to Mod_proxy
L Last Stop processing the next rule
N Next Again the first rule starts processing, but uses the current rewritten URL address
C Chain Link the current rule to the rule immediately followed
T Type Enforcing the specified MIME class
Ns Nosubreq Run this script only when there are no internal child requests executing
NC Nocase URL address matching is not case sensitive
QSA Qsappend Append the query string part to the new URL address instead of replacing the
Pt Passthrough Pass the rewritten URL address to another Apache module for further processing
S Skip After ignoring the rules
E Env Setting environment variables
Other uses of Rewritecond: "-D" (directory)    treats teststring as a pathname and tests whether it is an existing directory. "-F" (regular file)    treats teststring as a pathname and tests whether it is a regular file that exists. "-S" (non-empty regular file) treats    teststring as a pathname and tests whether it is an existing regular file with a size greater than 0. The "-L" (symbolic Connection)    treats teststring as a pathname and tests whether it is an existing symbolic connection. "-X" (executable)    treats teststring as a pathname and tests whether it is an existing file with executable permissions. This permission is detected by the operating system. "-F" (a file that exists on a child request)    checks 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 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)    checks 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 to do the check, because it will reduce the performance of the server, so please use it carefully!

Line four:

rewriterule Pattern Substitution [Flags] /* the pattern is the parameter, usually the extension of some files; substitution is used to replace the previous one; Here's the flags, refer to the table above, the usual R denotes redirect (forced redirection), F means forbidden (forbidden), L means last (final), and it is usually available when you want to stop the rewrite operation and immediately redirect. */
V. More examples of use:

1. Picture redirection

%{http_host} ^localhost$    // If the domain name is localhostrewritecond%{request_filename}!-f     //  and the file accessed cannot find rewriterule ^images/(. +) http://127.0.0.1/test/showimages/$1 [r=302,l]      //Jump to another directory under another domain to access this image

2, level two domain name redirection to www.yourdomain.com

Rewriteengine Onrewritecond%{http_host} ^yourdomain.com [Nc]rewriterule ^ (. *) $ http://www.yourdomain.com/$1 [R=301,L ]

3, the site upgrade, the temporary error page

Rewriteengine Onrewritecond%{request_uri}!/maintenance.html$     //If the requested address is not maintenance.htmlrewritecond%{REMOTE _ADDR}!^123.123.123.123       //Client IP if not this rewriterule $/error.html [r=302,l]                //Redirect to error.html This upgrade reminder page

4. redirect RSS address to Feedsky

Rewriteengine Onrewritecond%{http_user_agent}! FeedSky [Nc]rewritecond%{http_user_agent}! Feedvalidator [Nc]rewriterule ^feed/? ([_0-9a-z-]+)?/?$ http://feed.feedsky.com/yours

5. Prevent Directory Browsing:

Options all-indexes

6, 404 redirect

ErrorDocument 404/404.html

7. Set directory default page

DirectoryIndex about.html

Note: The permissions of the. htaccess are set to 644

Extended reading:

http://blog.neazor.com/?p=559

Http://www.cnblogs.com/ganiks/p/htaccess-get-started.html

Using. htaccess to implement Apache URL redirection

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.