Introduction to the Chinese configuration, usage, and syntax of Apache mod_rewrite (URL rewriting and anti-theft chain functionality)

Source: Internet
Author: User
Tags ftp connection

Dynamic content-driven Web sites that are backed up by a database are frequently experiencing these problems:

      • When you enter an invalid parameter in the address bar of the browser, a database error message appears, which is a security risk
      • Search engines can't ingest all of your pages
      • The link address of a Web page is a series of parameters that are difficult to understand for browsing users and search engines.


These problems can be solved by a basic module of Apache server mod_rewrite, the default installation of Apache will be installed this module. To enable this module, open the httpd.conf file to see if the following two lines are masked, the first line is to load the Mod_rewrite module, and the second line is to enable the module.

LoadModule Rewrite_module modules/mod_rewrite.so
Addmodule mod_rewrite.c

Mod_rewrite How does this module work?

Mod_rewrite intercepts URLs that meet certain criteria and rewrites them to the required URLs according to the set rules.

For example, a URL such as http://www.mysite.com/product.php?pid=123312 can be rewritten as
A static URL such as http://www.mysite.com/product-123312.html, or a more specific http://www.mysite.com/product/thinkpad-t42.html

Rules for overriding

An expression for the overridden rule:

Rewriterule mode substitution [options]

Rewriterule is a simple command to tell mod_rewrite how this module is going to be rewritten, the key point is that you can use regular expressions in patterns and substitutions to match the corresponding characters. The broad flexibility of regular expressions translates dynamic URLs into a variety of static URLs that meet requirements. Look at this rewrite rule:

rewriterule/products/([0-9]+)
/fancy/products.php?id=$1

When you enter http://www.mysite.com/product/123 in the browser address bar, this address is rewritten as http://www.mysite.com/fancy/product.php?id=123

In this way, visitors will not know what your program is really in that directory, the real name of the program, which also improves the safety of the site, such a URL is also removed? = These characters are easy for search engine bots to crawl your site.

With regular expressions, you can write more complex rewrite rules:

Rewriterule ^/products$/content.php
Rewriterule ^/products/([0-9]+) $/content.php?id=$1
Rewriterule ^/products/([0-9]+), ([ad]*), ([0-9]{0,3}), ([0-9]*), ([0-9]*$)]

The options for overriding the rule are

    • ' Forbidden ' or ' f '-403 forbidden
    • ' Gone ' or ' g '-410 Gone
    • ' Nocase ' or ' NC '-case sensitive
    • ' Next '/n '-back to the first rule
    • ' Skip=n ' or ' s=n '-skip the following N rules

Process Control

Mod_rewrite is a rule that executes overrides from top to bottom, if the URL matches the first rule, overrides according to the first rule and, if it does not, executes the second rule until the end. With Process control, you can define different rewrite rules in different situations. The format is:

Rewritecond Test Conditions Condition

These test conditions are:

    • HTTP variables: http_user_agent, Http_referer, Http_cookie, http_forwarded, Http_host, Http_proxy_connection, HTTP_ACCEPT
    • Nexus and requested variables: REMOTE_ADDR, Remote_host, Remote_user, Remote_ident, Request_method, Script_filename, Path_info, QUERY_ STRING, Auth_type
    • Server internal variables: document_root, server_admin, server_name, SERVER_ADDR, Server_port, Server_protocol, Server_software
    • System variables: time_year, Time_mon, Time_day, Time_hour, Time_min, Time_sec, Time_wday, time
    • Mod_rewrite Special values: Api_version, The_request, Request_uri,

For example, you can use Mod_rewrite to disable linking to your images from other websites:

Rewritecond%{http_referer}!^$
Rewritecond%{http_referer}!^http://localhost/.*$ [OR,NC]
Rewritecond%{http_referer}!^http://mysite.com/.*$ [OR,NC]
Rewritecond%{http_referer}!^http://www.mysite.com/.*$ [OR,NC]
Rewriterule. * *. (gif| Gif|jpg| JPG) $ http://mysite/images/bad.gif [L,r]





The simplest way to configure Apache Mod_rewrite :


On the internet to find a lot of articles on the configuration of Apache Mod_rewrite, found that this is the most useful, you need to refer to.

1, through the PHP provided by the phpinfo () function to view the environment configuration, through Ctrl+f find to "Loaded Modules", which lists all the Apache2handler has been opened module, if it includes "mod_rewrite", it has been supported, You no longer need to continue setup.
If "Mod_rewrite" is not turned on, open the directory under your Apache installation directory "/apache/conf/" under the httpd.conf file, through ctrl+f find to "LoadModule Rewrite_module", the previous " # "number to delete. If not found, go to the "LoadModule" area, add "LoadModule rewrite_module modules/mod_rewrite.so" (Required exclusive line) to the last line, and then restart the Apache server.

2, let Apache server Support ". htaccess"
How do I get my local Apache server to support the ". htaccess"? In fact, simply modify the Apache httpd.conf settings to allow Apache support. htaccess. Open a. httpd.conf file (where?) In the Conf directory of the Apache directory), when opened with a text editor, find
<directory/>
Options FollowSymLinks
AllowOverride None
</Directory>
Switch
<directory/>
Options FollowSymLinks
AllowOverride All
</Directory>
You can do it.

3. Create a ". htaccess" File
If it is under the Windows platform, I really do not know how to create a ". htaccess" file, because this file does not actually have a filename, only the extension, through the normal way is unable to build this file, don't worry, immediately tell you three ways:
Three ways to create a htaccess.txt text file (of course, the name of the text file you can take any), and then there are three ways to rename the file: (1) Open with Notepad, click File – Save As, enter ". htaccess" in the File name window, Note that the entire green section, which contains the quotation marks, is then clicked to save the line. (2) Go to cmd Command window, switch to the folder of the Htaccess.txt file by CD, then enter the command: Rename Htaccess.txt. htaccess, then click the keyboard enter key. (3) through the FTP connection Htaccess.txt folder, through the FTP software rename.
So we need to create a few ". htaccess" files, and what do they enter? The basic principle is that the root directory must have one, all requests for redirection (URL rewriting) will go to index.php (to the front controller), and a "./application" folder is required to deny all direct access to the contents of the folder (such as HTTP ://localhost/application/models/user.php), this is done because all access requests must be selected through the front-end controller to assign access, and secondly for security; ". htaccess" in the "./library" folder; Public folder must be built, because the folder's files are all directly accessible to the front-end, so you need to undo the URL rewrite. Here are the contents of the 4 "./htaccess" Files:
./.htaccess
Rewriteengine on
Rewriterule!/. (JS|ICO|GIF|JPG|PNG|CSS) $ index.php
./application/.htaccess
Deny from all
./library/.htaccess
Deny from all
./public
Rewriteengine off
In fact, the Apache URL rewriting function can also be set directly in the httpd.conf file, here is not specific, online related tutorials are also many.





Apache's Rewriterule rules are detailed:


R[=code] (Force redirect) forcing external redirection
Forces a http://thishost[:thisport]/prefix to be redirected to an external URL in an alternate string. If code is not specified, the default 302 HTTP status code will be used.
F(Force URL to is forbidden) disables the URL and returns the 403HTTP status code.
G(Force URL to is gone) forces the URL to gone and returns the 410HTTP status code.
P(Force proxy) forces the use of proxy forwarding.
L(last rule) indicates that the current rule is the final rule, stopping the rewrite of the rule after parsing.
N(Next round) re-runs the rewrite process starting with the first rule.
C(chained 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 (Force MIME type) coercion MIME type
NS(Used only if no internal sub-request) is used only for internal sub-requests
NC(no case) insensitive
QSA(Query string append) Append request string
NE(no URI escaping of output) does not escape special characters in the output
For example: rewriterule/foo/(. *)/bar?arg=p1/%3d$1 [R,ne] will be able to correctly convert/foo/zoo to/bar?arg=p1=zed
PT(pass through to next handler) passes to the next processing
For example:
Rewriterule ^/abc (. *)/def$1 [PT] # will be handed over to/def rule processing
Alias/def/ghi
S=num (skip next rule (s)) skips num rule
E=var:val (Set environment variable) setting environment variables

Rewrite Server variables:
HTTP headers:http_user_agent, Http_referer, Http_cookie, Http_host, http_accept
Connection & Request:remote_addr, query_string
Server Internals:document_root, Server_port, Server_protocol
System Stuff:time_year, Time_mon, Time_day

description of the rewrite rule expression:
. Match any single character
[chars] Match string: chars
[^chars] mismatch string: chars
TEXT1|TEXT2 selectable string: Text1 or Text2
? Match 0 to 1 characters
* Match 0 to more characters
+ match 1 to more characters
^ String Start flag
$ string End Flag
/n Escape Character flag

Reverse reference $N used for matching variable calls in Rewriterule (0 <= N <= 9)
Reverse reference%N for the last matching variable call in Rewritecond (1 <= N <= 9)

rewritecond identifier  
' nocase| NC ' (no case) ignores size  
' Ornext|or ' (or Next condition) logical OR, can match multiple rewritecond conditions simultaneously

Rewriterule Applicable markers
' Redirect| R [=code] ' (force redirect) forced rewrite for an external turn based on HTTP (note URL changes) such as: [R=301,l]
' Forbidden| F ' (Force URL to is forbidden) rewritten as forbidden access
' Proxy| P ' (force proxy) overrides the HTTP path that is accessed through the proxy
' Last| L ' (last rule) final rewrite rule flag, if matched, no longer executes subsequent rules
' Next| N ' (next round) loops the same rule until the match is not satisfied
' Chain| C ' (chained with next rule) if the rule is matched, continue with the following rules with the chain flag.
' Type| T=mime-type ' (Force MIME type) specifies MIME type
' Nosubreq| NS ' (used only if no internal sub-request) skipped if internal sub-request
' Nocase| NC ' (no case) ignore size
' Qsappend| QSA ' (query string append) append a string of queries
' Noescape|ne ' (no URI escaping of output) prohibits characters in the URL from being automatically escaped into%[0-9]+ form.
' Passthrough|pt ' (pass through to next handler) applies the rewrite results to the Mod_alias
' Skip| S=num ' (skip next rule (s)) skips a few rules
' Env| E=var:val ' (Set environment variable) Add environment variable

Actual operation

Example:
Rewriteengine on
Rewritecond%{http_user_agent} ^msie [Nc,or]
Rewritecond%{http_user_agent} ^opera [NC]
Rewriterule ^.*-[f,l] here "-" means no replacement, the browser for IE and opera visitors will be banned from access.

Example:
Rewriteengine on
Rewritebase/test
Rewritecond%{request_filename}.php-f
Rewriterule ([^/]+) $/test/$1.php
#for Example:/test/admin =/test/admin.php
Rewriterule ([^/]+)/.html$/test/$1.php [L]
#for Example:/test/admin.html =/test/admin.php

Restrict a catalog to display only pictures
< Ifmodule mod_rewrite.c>
Rewriteengine on
Rewritecond%{request_filename}!^.*/. (gif|jpg|jpeg|png|swf) $
Rewriterule. *$-[f,l]
</ifmodule>






Apache Module Mod_rewrite Comprehensive Chinese interpretation document: http://www.uplinux.com/download/doc/apache/ApacheManual/mod/mod_rewrite.html

Introduction to the Chinese configuration, usage, and syntax of Apache mod_rewrite (URL rewriting and anti-theft chain functionality)

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.