Nginx Rewrite rules

Source: Internet
Author: User

Location =/{# exact match/, the host name cannot be followed by any strings [configuration A]}location/{# Because all the addresses are/start, so this rule will match to all requests # but the regular and longest strings will first match [configuration B]}location/documents/{# matches any of the/documents/The address at the beginning of the match, and then continue to search down # only after the regular expression does not match, this article will take this one [configuration C]}location~/documents/ABC {# matches any of the/documents/The address at the beginning of the match, and then continue to search down # only after the regular expression does not match, this article will use this [configuration CC]}location^~/images/{# matches any of the/images/The address at the beginning of the match, after matching, stop searching for regular, the use of this article. [Configuration D]} Location~* \. (Gif|jpg|jpeg) $ {# matches all requests ending with gif,jpg or JPEG # However, all requestsThe image under/images/will be handled by Config D, because ^~I can't get to this regular. [Configuration E]}location/images/{# characters match to/images/, continue down, you'll find ^~.presence [configuration F]}location/images/ABC {# longest character matches to/IMAGES/ABC, continue down, you'll find ^~.existence # F is not related to the placement order of G [configuration G]}location~/images/abc/{# Only remove config D is valid: The longest match to the beginning of the Config G address, continue to search, matching to this rule, using [configuration H]}location~*/js/.*/\.js

Rule description

    • Exact match with = start
    • If only the request at the end of the root directory is matched in A, no strings can be followed.
    • ^~ begins with a URI that begins with a regular string, not a regular match
    • ~ Starts with a case-sensitive regular match;
    • ~* start indicates a case-insensitive regular match
    • /generic match, if there is no other match, any request will match to

Priority order
(location =) > (location full path) > (location ^~ path) > (Location ~,~* regular order) > (Location section start path) > (/)

According to the location above, the following matching examples are set up

/- config a exactly matches exactly, even if /index.html does not match /downloads/download.html -config B matches B, there is no match down , with B/images/1. gif--- configuration D matches to F, down to D, stop down/images/abc/def-  config D longest match to G, down to D, stop down you can see that any /images/ beginning with the start will match to D and stop, FG write here is meaningless, H is never round, here just to illustrate the match order /documents/ Document.html config C matches to C, and there is no match down, using C/documents/1. jpg, configuration e matches to C, Down regular match to e/documents/abc.jpg config cc longest match to C, down regular order match to CC, not down to e

So in actual use, the individual feels that there are at least three matching rule definitions, as follows

=/ {    proxy_pass http://tomcat:8080/index^~/static/ {    / webroot/static/~* \. (gif|jpg|jpeg|png|css|js| ico) $ {    /webroot/res// {    proxy_pass http://tomcat:8080/ }

Rewrite rules

The rewrite function is to implement URL rewriting and redirection in conjunction with regular expressions and flag bits using nginx-provided global variables or variables that you set yourself. Rewrite can only be placed in server{},location{},if{}, and can only work on strings that are outside of the domain name, except for parameters that are passed, such as Http://seanlook.com/a/we/index.php?id=1&u =str rewrite only for/a/we/index.php.

Syntax rewrite regex replacement [flag];

If the relative domain name or parameter string works, you can use global variable matching, or you can use the Proxy_pass reverse proxy.

show that rewrite and location function a bit like, can achieve jump, the main difference is that rewrite is within the same domain name to change the path to obtain resources, and location is a class of paths to do control access or reverse proxy, you can proxy_pass to other machines. In many cases rewrite will also be written in the location, and their order of execution is:

    1. Execute the rewrite directive for the server block
    2. Perform a location match
    3. Executes the rewrite directive in the selected location

If one of the step URIs is overridden, the loop executes 1-3 until the actual file is found and the loop exceeds 10 times, returning a Internal Server error error.

Flag Flag bit

 Last : Equivalent to Apache's [L] flag, indicating completion rewritebreak: Stop execution of subsequent rewrite instruction sets for the current virtual host Redirect: Returns 302 temporary redirect, the address bar displays the address after the jump permanent: Return 301 Permanent Redirect, the address bar will show the address after the jump

Because 301 and 302 cannot simply return a status code, there must also be a redirected URL, which is why the return instruction cannot return 301,302. Here the last and break differences are a bit difficult to understand:

Last is generally written in the server and if, and break is generally used in the location of a URL match that does not terminate the rewrite, that is, the new URL will go again from the server matching process, The match break and last after the break terminates the rewrite can prevent this match from continuing with the subsequent rewrite instruction

If directives and global variables

If judgment instruction
The syntax is the IF (condition) {...}, judging the given condition condition. If true, the rewrite instruction within the curly braces will be executed, and the If condition (conditon) can be anything like:

    • When an expression is just a variable, if the value is empty or any string starting with 0 is treated as false
    • When you directly compare variables and content, use = or! =
    • ~ Regular expression Match, ~* case-insensitive match,!~ case-sensitive mismatch

-F and!-f to determine if a file exists
-D and!-d to determine if a directory exists
-E and!-e to determine if a file or directory exists
-X and!-x to determine if a file is executable

For example

if($http _cookie ~*"id= ([^;] +)(?:;|$)") {Set $ID$1; } //if the cookie matches the regular, set the variable $id equal to the regular reference partif($request _method =POST) {return405;} //if the Submit method is post, the status 405 (method not allowed) is returned. Return cannot be returned 301,302if($slow) {limit_rate 10k;}//speed limit, $slow can be set via SET commandif(!-F $request _filename)    {break; Proxy_pass http://127.0.0.1;}//if the requested file name does not exist, the reverse proxy is to localhost. The break here is also a stop rewrite checkif($args ~ post= $) {rewrite^ http://example.com/permanent;}//If query string contains "post=140", permanently redirects to example.com Location~* \. (gif|jpg|png|swf|flv) $ {valid_referers none blocked www.someone.com www.somewhere.com; if($invalid _referer) {return404; } //anti-theft chain}

Global variables

The following is a global variable that can be used as an if judgment

    • $args: #这个变量等于请求行中的参数, same as $query_string
    • $content _length: Content-length field in the request header.
    • $content _type: The Content-type field in the request header.
    • $document _root: The value specified in the root instruction of the current request.
    • $host: Requests the Host header field, otherwise the server name.
    • $http _user_agent: Client Agent information
    • $http _cookie: Client cookie information
    • $limit _rate: This variable can limit the connection rate.
    • $request _method: The action requested by the client, usually get or post.
    • $remote _addr: The IP address of the client.
    • $remote _port: The port of the client.
    • $remote _user: The user name that has been validated by the Auth Basic module.
    • $request _filename: The file path of the current request, generated by the root or alias directive and the URI request.
    • $scheme: http method (such as Http,https).
    • $server _protocol: The protocol used by the request, usually http/1.0 or http/1.1.
    • $server _addr: The server address, which can be determined after a system call is completed.
    • $server _name: server name.
    • $server _port: The port number on which the request reached the server.
    • $request _uri: Contains the original URI of the request parameter, and does not contain a hostname, such as: "/foo/bar.php?arg=baz".
    • $uri: The current URI without the request parameter, $uri does not contain a hostname, such as "/foo/bar.html".
    • $document _uri: Same as $uri.

Example: http://localhost:88/test1/test2/test.php
$host: localhost
$server _port:88
$request _uri:http://localhost:88/test1/test2/test.php
$document _uri:/test1/test2/test.php
$document _root:/var/www/html
$request _filename:/var/www/html/test1/test2/test.php

Common regular

    • . : matches any character except line break
    • ? : Repeat 0 or 1 times
    • +: Repeat 1 or more times
    • *: Repeat 0 or more times
    • \d: Matching numbers
    • ^: Match the start of a string
    • $: Description of matching string
    • {n}: repeat n times
    • {N,}: Repeat N or more times
    • [C]: match a single character C
    • [A-z]: matches any of a-Z lowercase letters

The matching between the parentheses () can be referred to later by A $, which represents the contents of the second ().

Rewrite instances

HTTP {# Defines the image Log format Log_format Imagelog'[$time _local]'$image _file' '$image _type' '$body _bytes_sent' '$status;    # Turn on rewrite log rewrite_log on; server {root/home/www; Location/{# Rewrite rule information error_log logs/Rewrite.log Notice; # Note that there is a ' single quote ' to avoid {} rewrite'^/images/([a-z]{2})/([a-z0-9]{5})/(. *) \. (png|jpg|gif) $'/data?file=$3.$4; # Note that you cannot add the following rule to the Last"parameter, otherwise the following set instruction will not execute set $image _file $3; Set $image _type $4; } Location/Data {# Specifies the log format for the picture to analyze the picture type and size Access_log logs/Images.log Mian; Root/data/images; # Apply the variables defined earlier. Judge the first file is not in, not to judge the directory is not in, if not yet jump to the last URL try_files/$arg _file/image404.html; } Location= /image404.html {# Picture does not exist returns specific information return404 "Image not found\n"; }}

The request to form such as/images/ef/uh7b3/test.png, rewrite to/data?file=test.png, so match to Location/data, first see/data/images/ The Test.png file does not exist, if it exists then the normal response, if not present, overrides the Tryfiles to the new image404 location, and returns the 404 status code directly.

Rewrite ^/images/(. *) _ (\d+) x (\d+) \. (png|jpg|gif) $/resizer/$1. $4? width=$2&height=$3last;

A file request, such as/images/bla_500x400.jpg, is rewritten to the/resizer/bla.jpg?width=500&height=400 address and will continue to attempt to match the location.

Examples of two-layer redirects similar to Phalcon

Server {Listen the;        server_name localhost; #charset Koi8-R; Access_log logs/Localhost.access.log Main; Location/{root d:/WebRoot;        Index index.html index.htm index.php; } #error_page404/404. html; # REDIRECT Server error pages to the static page/50x.html error_page - 502 503 504/50x.html; Location= /50x.html {root html; } # Proxy The PHP scripts to Apache listening on127.0.0.1: the# #location~\.php$ {# Proxy_pass http://127.0.0.1;#} # Pass the PHP scripts to FastCGI server listening on127.0.0.1:9000 Location~\.php$ {root d:/WebRoot; Fastcgi_pass127.0.0.1:9000;            Fastcgi_index index.php;            Fastcgi_param script_filename $document _root$fastcgi_script_name;        Include Fastcgi_params; } Location/test/{root d:/WebRoot;            Index index.php; Rewrite^ (. *) $/test/sub/Break ; } Location/Sctopic {root d:/WebRoot;            Index index.php; Rewrite^\/sctopic$/sctopic/public Last; Rewrite^\/sctopic\/(. *) $/sctopic/public/$1  Last; } Location/sctopic/public/{root d:/WebRoot;            Index index.php; if(-F $request _filename)            {break; } rewrite^\/sctopic\/public (. *) (\.html|\.json) $/sctopic/public/index.php?_url=$1  Last; Rewrite^\/sctopic\/public (. *) $/sctopic/public/index.php?_url=$1  Last; } # Deny access to. htaccess files,ifApache's Document Root# concurs with Nginx'S One#location ~/\.ht {# deny all; #}    }

Nginx Rewrite rules

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.