Configuration tutorials for Location from scratch in Nginx

  • 2020-05-15 03:35:28
  • OfStack

Basic knowledge of

The matching order of location is "match regular first, match normal".

The matching order of location is actually "match normal first, then match regular". The reason for the misunderstanding is that regular matches overwrite normal matches

Nginx location configuration syntax

1. location [ = | ~ | ~* | ^~ ] uri { ... }

2. location @name { ... }

The location configuration can be configured in two ways

1. Prefix + uri (string/regular expression)

2.@ + name

A prefix meaning

= : exact match (must be all equal)

~ : case sensitive

~* : ignore case

^~ : just match the uri section

@ : internal service jump

Location basics

1.location is configured in the server block.

2. Different configurations can be used for different URI (configuration in location) to handle different requests.

3.location is sequential and will be processed by the first matched location.

Location configuration demo

1.=, exact match


  location = / {
   # The rules 
  }
  #  Match to  `http://www.example.com/`  This kind of request. 

2.~, case sensitive


  location ~ /Example/ {
    # The rules 
  }
  # Sample request 
  #http://www.example.com/Example/ [ successful ]
  #http://www.example.com/example/ [ failure ]

3.~*, case ignored


 location ~* /Example/ {
    # The rules 
 }
 #  Will be ignored  uri  Partial case 
 #http://www.example.com/Example/ [ successful ]
 #http://www.example.com/example/ [ successful ]

4.^~, only matches starting with uri


 location ^~ /img/ {
   # The rules 
 }
 # In order to  /img/  The first request will be matched 
 #http://www.example.com/img/a.jpg [ successful ]
 #http://www.example.com/img/b.mp4 [ successful ]

5.@, nginx internal jump


 location /img/ {
  error_page 404 @img_err;
 }
 
 location @img_err {
  #  The rules 
 }
 # In order to  /img/  The initial request, if the status of the link is  404 . It's going to match  @img_err  On this rule. 

conclusion

location in Nginx is not as hard to understand as you might imagine, so don't be afraid. Look for more information, try more. You'll get something.

reference

http://nginx.org/en/docs/http/ngx_http_core_module.html#location Unification 1 resource identifier

Related articles: