Nginx in location, rewrite use

A, location usage summary

The location can be requested in different ways, to a different positioning approach.

1.location usage

~ * /js/.*/ LOCATION \ .js 
In = beginning exact matching; if only the root end of the directory matches the request, can not be followed with any character string.
^ ~ At the beginning, showing uri string beginning with a conventional, not a regular matching
 with ~ the beginning, showing a case-sensitive match regular;
 to ~ * beginning indicates regular case-insensitive match
 begins with a /, generic matches, If no other match, any requests are matched to the

 Order matching location is the "first match regular, ordinary match again."

Correction: location of the matching sequence is actually "ordinary first match, then match the regular." I say, everyone will refute me, because by "ordinary first match, then match the regular" can not we usually customary press the "first match regular, then matched normal" experience to explain. My only temporarily explain here, the cause of this misunderstanding is: regular match will be covered by ordinary match.

Usage example 2.location

location regular writing:
  1. Exact match # /, the hostname can not take any string

location = / {
[ configuration A ]
}
 

      2. # all addresses starting with /, so this rule will default to the last match request

# But regular and will give priority to the longest string match
location / {
[ configuration B ]
}

   Example:

    LOCATION / { 
          proxy_pass HTTP: // server_pools; 
        } 
# This rule does not meet the only other requirements in order to match; will be the last match to the lowest degree of matching to achieve the above functions are: for example, the site is www.blog.com; back when nothing input, 
when other rules do not match, and finally to the server load balancing pool

    Match any addresses / documents / beginning, after matching in line, but also to continue down search 3. #
# When only back to the regular expression does not match, this one will be using this one

location /documents/ {
[ configuration C ]
}

 Example:

 
LOCATION / static / 
       { 
        rewrite ^ HTTP: // www.abc.com;       
       } 
# achieve the above functions: Suppose domain is www.blog.com; then configure the above functions are input www.blog.com / static / time , regardless of what is behind the static page (the page may not exist), 
then the same will eventually jump to www.abc.com this site.

     Match any addresses / documents / beginning, after matching in line, but also to continue down the search 4. #
# When only back to the regular expression does not match, this one will be using this one

 
location ~ /documents/Abc {
[ configuration CC ]
}

      5. # matches any address / images / the beginning of the match in line after regular stop down search, the use of this one.

location ^~ /images/ {
[ configuration D ]
}

         6. # match any gif, jpg, or jpeg end request
# However, all requests image / images / the config D will be processed, since it can not get ~ ^ a regular

location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}

 Example:

       7. # characters to match / images /, continue down, you will find there is ^ ~

location /images/ {
[ configuration F ]
}

       The longest matching character to # 8 / images / abc, continue down, will find that the presence of ^ ~
  # F. And the placement order is not related to G

location /images/abc {
[ configuration G ]
}

        9. # config D is valid only removed: first the longest matching address G at the beginning of config, search continues down to this match a regular, using

location ~ /images/abc/ {
[ configuration H ]
}
No order of priority:
(Location =)> (location full path)> (location ^ ~ Path)> (location ~, ~ * regular order)> (LOCATION initial path portion)> (/)
The above results matching:
According to the above location written, following the establishment of the matching example:
 / -> config A 
precisely exact match even / index.html not also match
 /downloads/download.html -> config B 
after matching B, down to no match, using B
 / Images / . 1 .gif -> Configuration D 
match to F, the matching down to D, stops down
 / Images / ABC / DEF -> config D 
longest match to G, down to match D, stopping down 
you to see any / / images at the beginning of the match will be stopped and D, FG write here is no sense, H never fail to get, and here only to illustrate the matching order
 /documents/document.html -> config C 
C to match, no match down, using the C
 / Documents / . 1 .jpg -> Configuration E 
matched C, down to match the regular E
 /documents/Abc.jpg -> config the CC 
longest match to C, down regular order to match CC, not down to E

3, practical recommendations

So the actual use, personally feel that there are at least three matching rules are defined as follows:
# Web site root directly matched by the domain name visit the Web site home page more frequently, using this will accelerate the process, the official website says. 
# Here is forwarded directly to the back-end application server, it can be a static Home
The first rule # Required = LOCATION / { 
proxy_pass http: // Tomcat: 8080 / index 
} 
# The second rule is Required static files request, which is a http server nginx strengths 
# has two configuration modes, directory suffix match or matches, optionally with the use of one or
LOCATION
^ ~ / static / { the root / Webroot / static / ; } LOCATION . * ~ \ (GIF | JPG | JPEG | PNG | CSS | JS | ICO) {$ root / Webroot / RES / ; } # the third rule is the general rule, to forward the request to the back-end application server dynamic
# static file requests on a non-default dynamic requests, after all, their own popular some of the current frame according to the actual grasp # with .php, where very few .jsp suffix
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

Two, Rewrite usage summary

     1.rewrite definition

     rewrite function is to use a global variable or variables provided by nginx set up their own, combined with regular expressions and flags achieve url rewrite and redirect.
    {} rewrite only on the Server, LOCATION {}, IF {}, and act only outside the string parameter passed behind the removed name. 
For example, HTTP: // seanlook.com/a/we/index.php?id=1&u=str only /a/we/index.php rewritten.

   2.rewirte of  grammar

        rewrite regex replacement [flag];
        If the parameter string relative to the domain name or function, can use global variables match, proxy_pass reverse proxy may be used.
       From the show to see the location and function of rewrite a bit like, can realize the jump. The main difference is that the rewrite is in the same domain to change the path of access to resources, and the location is a kind of path do control access or reverse proxy, you can proxy_pass to other machines .
Lower rewrite many cases will be written in the location where their execution order is:
. 1  the rewrite instruction execution server block
 2  performs the matching location
 . 3 the rewrite instruction execution location of the selected
If a step URI is rewritten, then re-execute cycle 1-3 until you find the file actually exists; cycle more than 10 times, 500 Internal Server Error error is returned.

flag flag

  • last: Apache corresponding to the [L] flag, indicating the completion rewrite
  • break: Follow-up rewrite instruction to stop execution of the current web hosting collection
  • redirect: 302 temporary redirect return address after the jump address bar displays
  • permanent: return 301 permanent redirect, address after the jump address bar displays
302 reasons and because only returns a status code, there must be redirected URL, which is the return instruction can not be simply unable to return to 301 and 302 of the 301.
Here the difference between last and break a little difficult to understand:
  1. last generally written in the server and if, rather break in general use in location
  2. After the last match does not terminate the url rewriting, that the new url from the server will then move again matching process, and terminate the rewrite match after break
  3. break and organizations can continue to rewrite last instruction behind

3.rewrite common regular

  • .: Matches any character except newline
  • ?: Repeat 0 or 1 times
  • +: Repeated one or more times
  • *: Repeat 0 or more times
  • \ D: matching numbers
  • ^: Matches the beginning of the string
  • $: The end of the match the string
  • {N}: n times
  • {N,}: n times or more times
  • [C]: matches a single character c
  • [Az]: az matches any one lowercase letter
A match between the contents of () parentheses, may later be referenced by $ 1, $ 2 represents the second front () the contents. Regular people get confused which is \ to escape special characters.

rewrite example

Example. 1:
HTTP {
# image log format defined
log_format imagelog '[$ time_local]' $ image_file The '' $ image_type '' $ body_bytes_sent '' $ Status;
# rewritable open log
rewrite_log ON;
 
Server {
the root / Home / WWW;
 
LOCATION / {
# rewrite rule information
the error_log logs / rewrite.log Notice;
# Note that use 'single quotation marks, to avoid} {
the rewrite' ^ / Images / ([AZ] {2}) / ([A-Z0 .. -9] {}. 5) / (*) \ (PNG | JPG | GIF) $ '/data?file=$3.$4;
# noted above can later add this rule "last" parameter, or below the instruction set executed will not
set image_file the $ $. 3;
set image_type $ $. 4;
}
 
LOCATION / Data {
# log format specified for the image, the type and size of images to analyze
access_log logs / images.log Mian;
the root / Data / images;
# application-defined variable front. First, the file is not in the judgment, not the judgment directory and then not, if not the last to jump to a url in
try_files / $ arg_file /image404.html;
}
LOCATION /image404.html = {
# image specific information does not exist return
return 404 "Image Not found \ n-";
}
}
 
of the form /images/ef/uh7b3/test.png request to rewrite /data?file=test.png, then matched to the location / data, look /data/images/test.png file exists or not, if there is a normal response, if there is no rewriting tryfiles a new image404 location, status code 404 directly returns.

Example 2:
rewrite ^ / ImagesRF Royalty Free / _ (\ d +) the X-(\ d +) \ (PNG | JPG | GIF) $ /resizer/$1.$4?width=$2&height=$3 Last; (*.).?
To shape as /images/bla_500x400.jpg file requests, /resizer/bla.jpg?width=500&height=400 rewritten to address, and will continue to try to match location.

if the global variable instruction

determining if the instruction Syntax
     if (condition)
      {...}
Conditions given condition is determined. If true, rewrite instructions within the braces will be executed, if the condition (conditon) may be any of the following elements:
When the expression is only a variable, the value is null, or if any string that begins with 0 as false will 
direct comparison of the variables and the contents, use = or! = 
~   Regular expression matching
 ~ * insensitive matching of
 ! ~   not case-sensitive match
 -f and -! F is used to determine whether there is a file
 -d and -! D for whether or not directory
 -e and -! E used to determine whether there is a file or directory
 -x and -x! It is used to determine whether an executable file
 
E.g:
Global Variables
The following may be used as the global variable is judged if
  • $ Args: # This variable is equal to the parameter line request, with $ query_string
  • $ Content_length: Request Content-length header field.
  • $ Content_type: request header Content-Type field.
  • $ Document_root: current value specified in the instruction root request.
  • $ Host: the host request 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: action requested by the client, usually GET or POST.
  • $ Remote_addr: IP address of the client.
  • $ Remote_port: client port.
  • $ Remote_user: Username Auth Basic Module has passed validation.
  • $ Request_filename: the file path of the current request, requested by the instruction root URI or alias generated.
  • $ Scheme: HTTP method (such as http, https).
  • $ Server_protocol: protocol requests, usually HTTP / 1.0 or HTTP / 1.1.
  • $ Server_addr: server address, after the completion of a system call can determine this value.
  • $ Server_name: server name.
  • $ Server_port: request reaches the server's port number.
  • $ Request_uri: contains the original request URI parameters, it does not include the host name, such as: "/ foo / bar.php arg = baz?".
  • $ Uri: with no request parameters of the current URI, $ uri does not contain a host name, such as "/foo/bar.html".
  • $ Document_uri: given $ uri homologous.

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

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160712.htm