Apache-rewrite+13 a classic case

Source: Internet
Author: User
Tags subdomain

Common applications for Apache rewrite rules (rewrite)

One: Purpose


This article is intended to provide an approach to how to use Apache rewrite rules to resolve some common URL rewriting methods, through common

Examples give users some basic methods and clues for using rewrite rules.


Two: Why do I need to use rewrite rules?

A Web site, if it is a long-term need to be placed on the Internet to provide services, there is bound to be constantly updated and maintained, such as pro

to other servers for maintenance, reorganize the directory structure, transform URLs and even change to new domain names, etc.

In order for customers to be unaffected by this, the best way is to use Apache Rewrite Rule (overriding

Rules).


Three: The scope of the rewrite rule

1) can be used in Apache Master config file httpd.conf

2) can be used in the virtual host configuration defined in the httpd.conf

3) You can use the span profile in the base directory. htaccess


Four: Application conditions for rewrite rules

Only when a user's Web request is eventually directed to the Apache background of a Web server, the Web server accepts

Incoming request, depending on the profile, whether the request is a master configuration or a virtual host, based on the user's request in the browser

URI to pair the rewrite rule and pair it according to the actual request path. Rewrite rules in htaccess. Finally put the request

Content is returned to the user, there are two possible types of responses:


1) external redirection (Redirect) of the content of the browser request to another URL.

Ask the browser to make a request again with a new Uri (r=301 or r=302, temporary or permanent redirect)

such as: A site has a formal URL and alias URL, the alias URL to redirect to the regular URL, or the site change

into a new domain.

REDIRECT the old domain name to the new domain name (Redirect)


2) may also be sent back to the customer by the Apache internal Sub-request agent to generate new content [P,l]

This is Apache internally according to the rewritten URI inside the request content through the proxy module and send back the content to the customer, while the customer

Browser does not know that the URI in the browser is not overwritten. But the actual content is obtained by Apache based on the URI of the rewrite rule.

such as: Apache running on the corporate firewall to start this proxy rewrite rule, agent on the internal network segment of the Web services

The request of the device.


Five: How does the rewrite rule work?

We assume that you have compiled mod_rewrite into a module when compiling Apache, and that you are sure that your httpd.conf has

LoadModule Rewrite_module libexec/mod_rewrite.so

And there are addmodule in the

Addmodule mod_rewrite.c

You can use rewrite rules.

When an external request comes to Apache,apache call the definition in the rewrite rule to override the request specified by the user's browser

URI, the last overridden URI is sent by the browser for another request if it is a redirect, and if the proxy overrides

After the URI to the proxy module to request the final content (contents), and finally send back to the browser.


Six: When to use the rewrite rule definition in. htaccess?

If you do not have administrator rights on the server where your site content resides, or if your site is placed on the ISP's server

On hosting and so on, you can't overwrite the master profile, but you can make the directory where your Web site content resides

Have write permission, then you can set your own. htaccess

The document achieves the same purpose. But you need to make sure that the main profile in the directory where your site is located is defined in the following

Capacity:


Options Indexes FollowSymLinks

AllowOverride All


Otherwise, your. htaccess won't work.


Seven: Application examples

Assuming that Apache is compiled and installed under the/usr/local/apache/directory of the host 192.168.1.56, we compile

The rewrite and proxy modules are translated into the.


1) hide a directory under Apache so that any requests for that directory are redirected to another file.


The realization method of a> httpd.conf


Let's put the part of the face down to/usr/local/apache/conf/httpd.conf.



Options Indexes FollowSymLinks

AllowOverride All

Rewriteengine on

Rewritebase/

Rewriterule ^ (. *) $ index.html.en [r=301]



Note: Rewriteengine on is a rewrite engine switch, and if set to off, any rewrite rule definitions will not be

The other advantage of this switch is that if you want to remove the rewrite rules temporarily, then turn off and then restart Apache.

You do not have to comment out the rewrite rules for the following strips.

The Rewritebase/function is if the section is rewritten in the following Rewriterule definition (file

Name Index.html.en) in front of no/, is relative to the directory, relative to this rewritebase after the definition is also

is/usr/local/apache/htdocs/index.html.en, otherwise, if there is no rewritebase/this

One item, it is rewritten as

[Url]http://192.168.1.56/usr/local/apache/htdocs/manual/index.html.en [/url], apparently

Not correct.


But here we can also not rewritebase/, but instead

Rewriteengine on

Rewriterule ^ (. *) $/index.html.en [r=301]

Or

Rewriteengine on

Rewriterule ^ (. *) $ [url]http://192.168.1.56/index.html.en [/url][r=301]


B>. How to implement Htaccess


Let's put the following part to Httpd.conf.



Options Indexes FollowSymLinks

AllowOverride All



and put the following part into the/usr/local/apache/htdocs/manual/.htaccess.

Rewriteengine on

Rewritebase/

Rewriterule ^ (. *) $ index.html.en [r=301]


Note: Any changes made to the file. htaccess do not require a restart of Apache.


Q: What if I redirect this manual directory to the user Jephe's own home directory?

Use the following. htaccess scenario.

Rewriteengine on

Rewritebase/~jephe/

Rewriterule ^ (. *) $ $ [r=301]


Requests for any files in the manual directory are redirected to the same file in the ~jephe directory.


2) Conversion of [Url]www.username.domain.com[/url] for Username home page request for

[Url]www.domain.com/username [/URL]


The request for http/1.1 includes a host:http header, which we can rewrite with the following rule set

[Url]http://www.username.domain.com/anypath [/url] to/home/username/anypath


Rewriteengine on

Rewritecond%{http_host} ^www\. [^.] +\.host\.com$

Rewriterule ^ (. +)%{http_host}$1 [C]

Rewriterule ^www\. ([^.] +) \.host\.com (. *)/home/$1$2


Note:

Rewritecond conditional rewrite rules that apply the following rewrite rules when the conditions defined later are met.

Rewritecond have various variables

, please refer to the relevant documentation.


3) Rewrite rules on the firewall proxy requests for servers on the internal network segment.


Namevirtualhost 1.2.3.4



servername [url]www.domain.com [/url]

Rewriteengine on

Proxyrequest on

Rewriterule ^/(. *) $ [url]http://192.168.1.3/$1 [/url][p,l]



Note: When an external browser requests [Url]www.domain.com[/url] to be resolved to the IP address 1.2.3.4, Apache surrenders

Mod_rewrite processing is converted into

[Url]http://192.168.1.3/$1[/url] After the agent module Mod_proxy to get the content to be transferred back to the user's browser.



4) Basic pre-set conversion map table to rewrite Rewritemap


convert [Url]www.domain.com/[/url]{countrycode}/anypath to URI specified in map table, above is virtual host

The definition in


Rewritelog/usr/local/apache/logs/rewrite.log

Rewriteloglevel 9


Rewriteengine on

Proxyrequest on

Rewritemap Sitemap Txt:/usr/local/apache/conf/rewrite.map

Rewriterule ^/([^/]+) +/(. *) $ [url]http://%[/url]{remote_host}::$1 [C]

Rewriterule (. *)::([a-z]+] $ ${sitemap:$2|[ Url]http://h.i.j.k/[/url]} [r=301,l]


The contents of the file/usr/local/apache/conf/rewrite.map are as follows:


sg [url]http://a.b.c.d/[/URL]

sh [url]http://e.f.g.h/[/url]


Note: When the user requests [Url]http://www.domain.com/sg/anypath[/url], it is rewritten as

[Url]http://a.b.c.d/anypath. [/URL]

When debugging is required, use Rewritelog and Rewriteloglevel 9 and 9 for maximum debug

Information

The minimum is 1, the minimum debugging information, the default is 0, no debugging information.

The syntax of a sitemap is ${sitemap:lookupkey | DefaultValue}, some books put $ into% is wrong

The wrong


-------------------------13 Classic Cases-------------------------------


1. Remove the WWW tag from the domain name

Copy the Code code as follows:

Rewritecond%{http_host}!^jb51\.net$ [NC]

Rewriterule.? Http://jb51.net%{request_uri} [R=301,l]


2. Remove the WWW tag, but save the subdomain

Copy the Code code as follows:

Rewritecond%{http_host} ^www\. ([A-z0-9_]+\.)? jb51\.net) $ [NC]

Rewriterule.? Http://%1%{request_uri} [R=301,l]


Here, when the 1% variable is matched, the subdomain is fetched in%2 (internal atom), which is exactly what we need for this%1 variable.

3. Add www tags to subdomains

Copy the Code code as follows:

Rewritecond%{http_host} ^ ([A-Z.] +)? jb51\.net$ [NC]

Rewritecond%{http_host}!^www\. [NC]

Rewriterule.? Http://www.%1jb51.net%{request_uri} [R=301,l]


This rule crawls the%1 variable of level two domain name, if not start with www, then add www, the former domain name and {Request_uri} will follow after.

4. Prevent picture hotlinking

Some webmasters are unscrupulous in hotlinking your pictures on their website, consuming your bandwidth. You can add code to block this behavior.

Copy the Code code as follows:

Rewritecond%{http_referer}!^$

Rewritecond%{http_referer}!^http://(www\.)? jb51\.net/[NC]

Rewriterule \. (gif|jpg|png) $–[f]


If the {http_referer} value is not empty or is not from your own domain name, this rule uses [F]flag to block URLs ending with gif|jpg|png

If you are determined to despise this hotlinking, you can also change the picture so that users who visit the hotlinking site know that the site is stealing your pictures.

Copy the Code code as follows:

Rewritecond%{http_referer}!^$

Rewritecond%{http_referer}!^http://(www\.)? jb51\.net/.*$ [NC]

Rewriterule \. (gif|jpg|png) $ your picture address [r=301,l]


In addition to blocking the picture hotlinking link, the above rule replaces its hotlinking image with the picture you set.

You can also block specific domain names from hotlinking your images:

Copy the Code code as follows:

Rewritecond%{http_referer}!^http://(www\.)? leech_site\.net/[NC]

Rewriterule \. (gif|jpg|png) $–[f,l]


This rule will block all image link requests on the domain name blacklist.

Of course, these rules are based on {http_referer} to get the domain name, if you want to use the IP address, with {REMOTE_ADDR} can be.

5. Redirect to page 404 If file does not exist

If your host does not provide a 404 page redirection service, then we create it ourselves.

Copy the Code code as follows:

Rewritecond%{request_filename}!-f

Rewritecond%{request_filename}!-d

Rewriterule.? /404.php [L]


Here-F matches the existence of the file name, and-D matches the existence of the path name. This code will determine if your file name and path name exist before you make a 404 redirect. You can also add a. url=$1 parameter to the 404 page:

Copy the Code code as follows:

Rewriterule ^/? (. *) $/404.php?url=$1 [L]


This way, your 404 page can do something else, such as default confidence, send an email alert, add a search, and so on.

6. Renaming a directory

If you want to rename the directory on the site, try this:

Copy the Code code as follows:

Rewriterule ^/?old_directory/([a-z/.] +) $ new_directory/$1 [r=301,l]


In the rules I added a "." (Note that not all characters are represented, preceded by an escape character) to match the file's suffix name.

7. Convert. html suffix names to. php

If the. html file can continue to be accessed, update your site link.

Copy the Code code as follows:

Rewriterule ^/? ([a-z/]+) \.html$ $1.php [L]


This is not a Web redirect, so the visitor is not visible. Let him as a permanent redirect (visible), change the flag to [r=301,l].

8. Create a no file suffix name link

If you want to make the link to your PHP site more concise and easy to remember-or to hide the file's suffix name, try this:

Copy the Code code as follows:

Rewriterule ^/? ([a-z]+) $ $1.php [L]


If the site is mixed with PHP and HTML files, you can use Rewritecond to determine if the suffix file exists, and then replace it:

Copy the Code code as follows:

Rewritecond%{request_filename}.php-f

Rewriterule ^/? ([a-za-z0-9]+) $ $1.php [L]

Rewritecond%{request_filename}.html-f

Rewriterule ^/? ([a-za-z0-9]+) $ $1.html [L]


If the file is suffixed with. PHP, this rule will be executed.

9. Check for specific parameters in query variables

If there is a special parameter in the URL, you can use Rewritecond to identify whether it exists:

Copy the Code code as follows:

Rewritecond%{query_string}!uniquekey=

Rewriterule ^/?script_that_requires_uniquekey\.php$ other_script.php [qsa,l]


The above rule will check if the UniqueKey parameter exists in {query_string}, and if the {Request_uri} value is Script_that_requires_uniquekey, it will be directed to the new URL.

10. Delete a query variable

Apache's Mod_rewrite module automatically recognizes query variables unless you make the following changes:

a). Assign a new query parameter (you can save the original query variable with [Qsa,l]flag])

b). Add a "?" after the file name (e.g. index.php?). Symbol "?" Does not appear in the browser's address bar.

11. Present the current URI in a new format

If this is the urls:/index.php?id=nnnn we are currently running. We very much want to change it to/nnnn and let the search engine show in the new format. First, we have to redirect the old URLs to the new format in order for the search engine to be updated, but we also have to make sure that the previous index.php still works. Did I get confused?

The trick is to add a tag "marker" that the visitor cannot see in the query variable. We redirect only the links in the query variable that do not appear in the "marker" tag, and then replace the original chain with the new format, and add a "marker" tag to the existing parameter by [Qsa]flag]. Here's how it's implemented:

Copy the Code code as follows:

Rewritecond%{query_string}!marker

Rewritecond%{query_string} id= ([-a-za-z0-9_+]+)

Rewriterule ^/?index\.php$%1? [R=301,l]

Rewriterule ^/? ([-a-za-z0-9_+]+) $ index.php?marker &id=$1 [L]


Here, the original url:http://www.jb51.net/index.php?id=nnnn, does not contain marker, so the first rule is permanently redirected to http://www.jb51.net/nnnn, the second rule will be HTTP// WWW.JB51.NET/NNNN redirects to http://www.jb51.net/index.php?marker&id=nnnn, and adds marker and id=nnnn two variables, and finally Mod_ Rewrite begins the processing process.

Second match, marker is matched, so ignore the first rule, here is a "." The characters appear in http://www.jb51.net/index.php?marker&id=nnnn, so the second rule is ignored, so we're done.

Note that this solution requires some extensions to Apache, so if your site is placed on a shared host you will encounter many obstacles.

12. Ensure security Service is enabled

There are two ways Apache can tell if you've turned on security services, referencing {HTTPS} and {Server_port} variables, respectively:

Copy the Code code as follows:

Rewritecond%{request_uri} ^secure_page\.php$

Rewritecond%{https}!on

Rewriterule ^/? (secure_page\.php) $ https://www.jb51.net/$1 [r=301,l]


The above rule tests whether the {Request_uri} value equals our secure page code, and {HTTPS} is not equal to on. If both conditions are met, the request is redirected to the Security Service URI. In addition you can use {Server_port} to do the same test, 443 is a common Security service port

Copy the Code code as follows:

Rewritecond%{request_uri} ^secure_page\.php$

Rewritecond%{server_port}!^443$

Rewriterule ^/? (secure_page\.php) $ https://www.jb51.net/$1 [r=301,l]


13. Enforce security services on a specific page

There is a secure service domain name and a non-secure service domain name under the same server root, so you need to use Rewritecond to determine if the security service port is occupied and only the page requirements for the following list are security services:

Copy the Code code as follows:

Rewritecond%{server_port}!^443$

Rewriterule ^/? (PAGE1|PAGE2|PAGE3|PAGE4|PAGE5) $ https://www.jb51.net/%1[r=301,l]


Here's how to return a page that is not set up as a security service to port 80:

Copy the Code code as follows:

Rewritecond%{Server_port} ^443$

Rewriterule!^/? (PAGE6|PAGE7|PAGE8|PAGE9) $http://www.jb51.net%{request_uri} [R=301,l]

In fact, the most used in rewrite should be the regular expression, if you know a little regular, write this rule is relatively simple.








Apache-rewrite+13 a classic case

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.