Apache Address Rewriting instance two, Rewritecond and Rewriterule used together

Source: Internet
Author: User
Tags php file php and subdomain subdomain name

1. Add www tags to subdomains
Rewritecond%{http_host} ^ ([A-Z.] +)? example\.com$ [NC] Rewritecond%{http_host}!^www\. [NC] Rewriterule.? Http://www.%1example.com%{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.

2. Remove the WWW tag in the domain name Rewritecond%{http_host}!^example\.com$ [NC] rewriterule.? Http://example.com%{request_uri} [R=301,l]

3. Remove the WWW tag, but save the subdomain name Rewritecond%{http_host} ^www\. ([A-z0-9_]+\.)? example\.com) $ [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.
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.

Rewritecond%{http_referer}!^$

Rewritecond%{http_referer}!^http://(www\.)? example\.com/[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.

Rewritecond%{http_referer}!^$

Rewritecond%{http_referer}!^http://(www\.)? example\.com/.*$ [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:

Rewritecond%{http_referer}!^http://(www\.)? leech_site\.com/[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.

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:

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:

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.

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:

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:

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:
<

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:

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.example.com/index.php?id=nnnn, which does not contain marker, is permanently redirected to http://www.example.com/nnnn by the first rule, The second rule redirects http://www.example.com/nnnn to http://www.example.com/index.php?marker&id=nnnn and adds marker and id= NNNN two variables, and finally mod_rewrite begins the process.
Second match, marker is matched, so ignore the first rule, here is a "." The characters appear in Http://www.example.com/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:

Rewritecond%{request_uri} ^secure_page\.php$

Rewritecond%{https}!on

Rewriterule ^/? (secure_page\.php) $ https://www.example.com/$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

Rewritecond%{request_uri} ^secure_page\.php$

Rewritecond%{server_port}!^443$

Rewriterule ^/? (secure_page\.php) $ https://www.example.com/$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:

Rewritecond%{server_port}!^443$

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

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

Rewritecond%{Server_port} ^443$

Rewriterule!^/? (PAGE6|PAGE7|PAGE8|PAGE9) $http://www.example.com%{request_uri} [r=301,l]<
Apache mod_rewrite Rules rewrite flags at a glance

1) R[=code] (force redirect) forced 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. 2) F (force URL to is forbidden) disables the URL and returns the 403HTTP status code. 3) G (force URL to is gone) forces the URL to gone and returns the 410HTTP status code. 4) P (force proxy) enforces the use of proxy forwarding. 5) L (last rule) indicates that the current rule is the final rule, stopping the rewrite of the rule after parsing. 6) N (next round) re-run the rewrite process starting with the first rule. 7) C (chained with next rule) is associated with the next law
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) enforces MIME type 9) NS (used only if no internal sub-request) is used only for not internal sub-requests) NC (no case) is insensitive to case) Q SA (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) Pass to the next process for example:
Rewriterule ^/abc (. *)/def$1 [PT] # will be handed over to/def rule processing
Alias/def/ghi) S=num (skip next rule (S)) Skip num Rules () e=var:val (set environment variable) set environment variables

URL Redirection Instance

Example one: (by accessing the previous a jump to the back of B)

1.http://www.zzz.com/xxx.php-> http://www.zzz.com/xxx/

Features of the 2.http://yyy.zzz.com-> http://www.zzz.com/user.php?username=yyy

Rewriteengine on

Rewritecond%{http_host} ^www.zzz.com

Rewritecond%{request_uri}!^user\.php$

Rewritecond%{request_uri} \.php$

Rewriterule (. *) \.php$ http://www.zzz.com/$1/[R]

Rewritecond%{http_host}!^www.zzz.com

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

Rewriterule ^ ([^\.] +) \.zzz\.com http://www.zzz.com/user.php?username=$1

Example two:

/type.php?typeid=*–>/type*.html

/type.php?typeid=*&page=*–>/type*page*.html

Rewriterule ^/type ([0-9]+). html$/type.php?typeid=$1 [PT]

Rewriterule ^/type ([0-9]+) page ([0-9]+). html$/type.php?typeid=$1&page=$2 [PT]

Example three: hiding the index.php file

Rewritecond%{request_filename}!-d

Rewritecond%{request_filename}!-f

Rewriterule ^ (. *) $ index.php/$1 [qsa,pt,l]

One of the problems encountered in the work is that the redirected configuration of the write does not take effect correctly, the configuration in the httpd.conf file is valid, but the. htaccess file does not take effect,

Viewing files is always found

LoadModule Rewrite_module modules/mod_rewrite.so

<directory/>

Options FollowSymLinks

AllowOverride All

Order Deny,allow

Deny from all

</Directory>

It's all open. However, no matter how the configuration is invalid, refer to the official manual found:. htaccess configuration Required conditions:

The first is to open the mod_rewrite:

LoadModule Rewrite_module modules/mod_rewrite.so

<directory/>

Options FollowSymLinks

AllowOverride All

Order Deny,allow

Deny from all

</Directory>

The second step needs to be introduced. Htaccess (that is, change the following allowoverride none to allowoverride all: the role of the introduction. htaccess file)

<directory "/usr/local/apache/htdocs" >

#

# Possible values for the Options directive is "None", "all",

# or any combination of:

# Indexes includes followsymlinks symlinksifownermatch execcgi multiviews

#

# Note that "MultiViews" must is named *explicitly*-"Options All"

# doesn ' t give it to you.

#

# The Options directive is both complicated and important. Please see

# http://httpd.apache.org/docs/2.2/mod/core.html#options

# for more information.

#

Options-indexes FollowSymLinks includes

#

# AllowOverride Controls What directives is placed in. htaccess files.

# It can be ' all ', ' None ', or any combination of the keywords:

# Options FileInfo authconfig Limit

#

AllowOverride None

#

# Controls who can get stuff from the this server.

#

Order Allow,deny

Allow from all

</Directory>

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.