The method of Location configuration from scratch in Nginx

10-16-2023

basic knowledge

The matching order of location is to match regular first, and then to match ordinary.

In fact, the matching order of location is to match ordinary first, and then to match regular. The reason for misunderstanding is that regular matching will overwrite ordinary matching.

Nginx location configuration syntax

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

2. location @name { ... }

Location configuration can be configured in two ways.

1. Prefix+uri (string/regular expression)

2.@ + name

Prefix meaning

=: Exact match (all must be equal)

~: Case sensitive

~ *: Ignore case

~: just match the uri part

@: internal service jump

Basic knowledge of location

1.location is configured in the server block.

2. You can use different configurations (configurations in location) according to different URIs to handle different requests.

3.location is sequential and will be handled by the first matching location.

Location configuration demo

1.=, exact match

Location =/{# rule} # matches the request of http://www.example.com/.

2.~, case sensitive

Location ~ /example/ {# rule} # Request example # http://www.example.com/example/[success] # http://www.example.com/example/[failure]

3.~*, case ignored

Location ~* /example/ {# rule} # will ignore the case of the uri part # http://www.example.com/example/[success] # http://www.example.com/example/[success].

4. ~, only matches that start with uri

Location ^~ /img/ {# rule} # Requests that start with /img/ will be matched with # http://www.example.com/img/a.jpg [success] # http://www.example.com/img/b.mp4 [success].

5.@, nginx internal jump

location /img/ { error_page 404 @img_err; } location @img_err {# Rule} # Requests starting with /img/ if the link status is 404. It will match the rule @img_err.

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us