Nginx location Configuration

Source: Internet
Author: User

An example:

Location =/{# exact Match/, cannot carry any string after hostname [configuration A]}location/{# because all the addresses start with/, so this rule will match all requests# but regular and longest strings match [configuration B]}location/documents/{# Match any address that starts with/documents/, match later, and continue searching down# only the following regular expression does not match, this one will take this one [configuration C]}location ~/documents/abc {# Match any address that starts with/documents/, match later, and continue searching down# only after the following regular expression does not match, this article will take this one [configuration CC]}location ^~ / images/{# matches any address that begins with/images/, matches later, stops searching for regular, uses this. [Configuration D]} Location ~* \. (gif|jpg|jpeg) $ {# matches all requests ending with gif,jpg or JPEG # However, all requests/images/ The image below will be processed by Config D because ^~ cannot reach this regular [configuration E]}location /images/{# character matches to/images/, continue down, you will find ^~ exists [configuration F]}location/images/abc {# longest character matches to/I MAGES/ABC, continue down, you will find ^~ exists # F is not related to the placement order of G [Configuration G]}location ~ /images/abc/{# only remove config D is valid: First the longest match config G beginning address, continue to search, matching to this regular, using [Configuratio N H]}location ~* /js/.*/\.js 

    • An = exact match is already prefaced
      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

Sequential no priority:
(location =) > (location full path) > (location ^~ path) > (Location ~,~* regular order) > (Location section start path) > (/)

The above matching results
According to the location above, the following sample matches are set up:

    • /-Config A
      Exactly match exactly, even if/index.html doesn't match.
    • /downloads/download.html-config B
      After matching B, there is no match down, using B
    • /images/1.gif, Configuration D
      Match to F, match down to D, stop down
    • /images/abc/def-config D
      Longest match to G, down match D, stop down
      You can see that any/images/beginning with a 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
      Match to C, there is no match down, use C
    • /documents/1.jpg, Configuration E
      Match to C, down to regular to E
    • /documents/abc.jpg-config CC
      Longest match to C, down regular order to CC, not down to E
Practical Use recommendations
所以实际使用中,个人觉得至少有三个匹配规则定义,如下:#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。#这里是直接转发给后端应用服务器了,也可以是一个静态首页# 第一个必选规则location = / {    proxy_pass http://tomcat:8080/index}# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用location ^~ /static/ { root /webroot/static/;}location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { root /webroot/res/;}#第三个规则就是通用规则,用来转发动态请求到后端应用服务器#非静态文件请求就默认是动态请求,自己根据实际把握#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了location / { proxy_pass http://tomcat:8080/}

Http://tengine.taobao.org/book/chapter_02.html
Http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

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 the name of the drop passed argument, such as http://seanlook.com/a/we/index.php?id=1&u=str only/a/we/index.php overrides. Grammarrewrite 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 rewrite
    • break: Stop executing the subsequent rewrite instruction set for the current virtual host
    • redirect: Returns 302 temporary redirect, the address bar will show the address after the jump
    • permanent: Returns 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:

    1. Last is generally written in server and if, and break is generally used in location
    2. Last does not terminate the rewritten URL match, that is, the new URL will go through the matching process again from the server, and break terminates the rewritten match
    3. Break and last can prevent the subsequent rewrite instructions from being executed.
If directives and global variables

If judgment instruction
The syntax is to if(condition){...} judge a 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 comparing variables and content directly, use = or!=
    • ~Regular expression matching, case ~* -insensitive match, !~ case-sensitive mismatch

-fand !-f used to determine if a file exists
-dand !-d used to determine if a directory exists
-eand !-e used to determine if a file or directory exists.
-xand !-x used to determine if a file is executable

For example:

if ($http _user_agent ~ MSIE) {Rewrite ^ (. *) $/msie/$break;} If the UA contains"MSIE", rewrite request to/msid/directoryif ($http _cookie ~*"Id= ([^;] +)(?:;|$)") {Set$id$; }//If the cookie matches the regular, set the variable$id equals the regular reference partif ($request _method = POST) {Return405;} If the Submit method is post, the status is returned405 (Method not allowed).Return cannot be returned301,302if ($slow) {Limit_rate10k;} Speed limit, $slow can be set class= hljs-built_in ">set" if (!-f  $request _filename) {break; proxy _pass http://127.0. 0.1; }//If the requested file name does not exist, reverse proxy to localhost. Here break is also stop rewrite check if ($ args ~ Post=140) {rewrite ^ http://example.com/permanent;}//If query string contains " post=140 ", permanently redirected to Example.comlocation ~* \. (gif|jpg|png|swf|flv) $ {valid_referers none blocked www.jefflei.com www.leizhenfang.com; if ( $invalid _referer) {return 404;} Anti-Theft chain}                

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

  • $args: #这个变量等于请求行中的参数, with$query_string
  • $content_length: The 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 authenticated by the Auth Basic module.
  • $request_filename: The file path of the current request, generated by a root or alias instruction with a 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 the 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.

Cases: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: Match numbers
    • ^: Matches the start of a string
    • $: Description of matching string
    • {n}: Repeats n times
    • {n,}: Repeat N or more times
    • [c]: Matches a single character C
    • [a-z]: Matches any of a-Z lowercase letters

The () matching between the parentheses can be referenced later by, which represents the contents of the second in the $1 $2 previous () section. What's confusing in regular is \ escaping special characters.

Rewrite instances
HTTP {# define Image Log formatLog_format Imagelog‘[$time _local] '$image _file‘ ‘$image _type‘ ‘$body _bytes_sent‘ ‘$status;# Turn on rewrite logRewrite_logOnserver {root/home/www;Location/{# Rewrite rule informationError_log Logs/rewrite.logNotice# Note that there is a ' single quote ' to avoid {}Rewrite' ^/images/([a-z]{2})/([a-z0-9]{5})/(. *) \. (png|jpg|gif) $ '/data?file=$.$4;# note that the "last" parameter cannot be appended to the above rule, otherwise the following set instruction will not execute set  $image _file $3; set  $image _type $4;} location/data {# Specify 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 first the 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 return specific information return 404 " image not found\n ";}}    

 

The request of the shape, /images/ef/uh7b3/test.png rewrite to /data?file=test.png , then match to, location /data first look at the /data/images/test.png file does not exist, if there is a normal response, if it does not exist then rewrite tryfiles to the new image404 location, directly return 404 status Code.

Example 2:

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

The file request for the shape /images/bla_500x400.jpg , rewritten to the /resizer/bla.jpg?width=500&height=400 address, and will continue to try to match the location.

Example 3:
See SSL partial page encryption.

Reference

      • Http://www.nginx.cn/216.html
      • http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/
      • "Old Monk series Nginx rewrite rules quickly get started." PDF
      • http://fantefei.blog.51cto.com/2229719/919431
 

Nginx location Configuration

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.