location and rewrite in Nginx

location and rewrite in Nginx

1, Common Nginx regular expressions

^ : Matches the starting position of the input string
$ : Matches the end of the input string
* : Matches the preceding character zero or more times. As“ ol*"Can match“ o"And“ ol","oll"
+ : Matches the preceding character one or more times. As“ ol+"Can match“ ol"And“ oll","olll",But it can't match“ o"
? : Matches the preceding character zero or once, for example“ do(es)?"Can match“ do"Or“ does","?"Equivalent to "{0,1}"
. : Matching Division“\n"Any single character other than, to match, include“\n"Any character, such as“[.\n]"Patterns like
\ : Mark the following characters as a special character or a literal character or a backward reference. As“\n"Matches a newline character, and“\$"Then match“ $"
\d : Match pure numbers
{n} : repeat n second
{n,} : repeat n Times or more
{n,m} : repeat n reach m second
[] : Define the matching character range
[c] : Match single character c
[a-z] : matching a-z Any of the lowercase letters
[a-zA-Z0-9] : Match all upper and lower case letters or numbers
() : Start and end positions of expressions
| : OR operator 

2, location

1. location can be roughly divided into three categories

Exact match: location = / {}
General matching: location / {}
Regular matching: location ~ / {}

2. Common matching rules for location:

= : Exact matching of ordinary characters, that is, complete matching.
^~ : Indicates normal character matching. Use prefix matching. If the match is successful, no other will be matched location. 
~ : Case sensitive matching.
~* : Case insensitive matching.
!~ : Case sensitive matches are not matched.
!~* : Case insensitive matches are not matched.

3. location priority:

First, exact matching =
Secondly, prefix matching ^~
The second is regular matching according to the order in the file ~or~*
Then match the prefix without any decoration
 Finally, give it to / Universal matching

4. location example description:

(1)location = / {}
=For exact matching / ,The host name cannot be followed by any string, such as access / and /data,be / Match,/data Mismatch
 Another example location = /abc,Then only match/abc ,/abc/or /abcd No match. if location  /abc,Then match/abc ,/abcd/ Also match /abc/. 

(2)location / {}
Because all addresses start with /, this rule will match all requests, such as accessing / and / data, then / matches and / data also matches,
But if regular expression is followed, it will match longest string first (longest match)

(3)location /documents/ {}
Match any address starting with / documents /. After matching, continue to search for other location s
This rule will be used only when the regular expressions behind other location s do not match

(4)location /documents/abc {}
Match any address starting with / documents/abc. After matching, continue to search for other location s
This rule will be used only when the regular expressions behind other location s do not match

(5)location ^~ /images/ {}
Match any address starting with / images /. After matching, stop searching for the regular and adopt this one

(6)location ~* .(gif|jpg|jpeg)$ {}
Match all requests ending in gif, jpg, or jpeg
However, all the pictures under the request / images / will be processed by location ^~ /images /, because ^ ~ has a higher priority, so it can't reach this rule

(7)location /images/abc {}
The longest character matches to / images/abc, with the lowest priority. Continue to search for other location s, and you will find that ^ ~ and ~ exist

(8)location ~ /images/abc {}
If the match starts with / images/abc, the priority level will be followed. This item will be adopted only when location ^~ /images / is removed

(9)location /images/abc/1.html {}
Match / images / ABC / 1 HTML file, if and regular ~ / images / ABC / 1 Regular has a higher priority than HTML

Priority summary:
(location =) > (location full path) > (location ^ ~ path) > (location, * regular order) > (location partial starting path) > (location /)

5. In actual website use, there are at least three matching rule definitions

First required rule
Directly match the website root and visit the website home page through the domain name more frequently. Using this will speed up the processing, such as the official website.
This is directly forwarded to the back-end application server, or it can be a static home page

location = / {
    proxy_pass http://tomcat_server/;
}

Second required rule
Handle static file requests, which is the strength of nginx as an http server
There are two configuration modes, directory matching or suffix matching. Choose one or use it together

location ^~ /static/ {
    root /webroot/static/;
}

location ~* .(html|gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/;
}

Third rule
General rules, such as those used to forward tapes php,. Dynamic request of jsp suffix to back-end application server
Non static file requests are dynamic requests by default

location / {
    proxy_pass http://tomcat_server;
}

3, rewrite

The rewrite function is to use the global variables provided by nginx or the variables set by itself, combined with regular expressions and tags to realize URL rewriting and redirection.
For example: after changing the domain name, you need to keep the old domain name can be transferred to the new domain name, a web page needs to jump to the new page, the website anti-theft chain and so on.

rewrite can only be placed in server {}, location {}, if {}, and can only work on the string after the domain name excluding the passed parameters by default.
For example: http://www.lic.com/a/we/index.php?id=1&u=str Only for / A / we / index PHP rewrite.

1. rewrite jump implementation

Nginx: through ngx_http_rewrite_module module supports URL rewriting and if condition judgment, but not else
Jump: jump from one location to another. The loop can be executed up to 10 times. After that, nginx will return 500 errors
PCRE supports: perl compatible regular expression syntax rule matching
Rewrite the module set instruction: create a new variable and assign a value to it

2. rewrite execution sequence

1. Execute the rewrite instruction in the server block
2. Perform location matching
3. Execute the rewrite instruction in the selected location

3. rewrite syntax format

grammar rewrite<regex><replacement><flag>;
regex:Represents a regular matching rule
replacement:Indicates the content after jump
flag:express rewrite Supportive flag sign

4. Flag flag description

last: after this rule is matched, continue to match the new location URI rule downward, which is generally used in server and if.
break: this rule will terminate upon completion of matching. It will no longer match any of the following rules. It is generally used in location.
redirect: return 302 temporary redirection, and the browser address will display the URL address after the jump.
Permanent: return 301 permanent redirection, and the URL address after jump will be displayed in the browser address bar.

4, rewrite example

1. Domain name based jump

Now the old domain name of the company is www.lic Com has business requirements changed, and the new domain name www.kiki.com needs to be used Com instead, but the old domain name cannot be abolished. You need to jump to the new domain name, and the following parameters remain unchanged.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com.access.log;		#Log modification
	location / {
	#Add domain name redirection
        if ($host = 'www.lic.com'){						            #$host is the rewrite global variable, which represents the request host header field or host name
			rewrite ^/(.*)$ http://www.kiki.com/ permanent; 		#$ 1 is the content of regular matching, that is, the string behind the domain name
        }
        root   html;
        index  index.html index.htm;
    }
}





echo "192.168.184.10 www.lic.com www.kiki.com" >> /etc/hosts


systemctl restart nginx

Browser input simulation access http://www.lic.com/test/1.html
Will jump to www.kiki.com com/test/1. HTML, you can see the return 301 by viewing the element, which realizes the permanent redirection jump, and the parameters after the domain name jump normally.

2. Jump based on client IP access

Today, the new version of the company's business went online, requiring all IP access to display a fixed maintenance page for any content. Only the company's IP: 192.168.184.10 is accessed normally.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com-access.log  main;		#Log modification
#Set legal IP tag
set $rewrite true;							#Set the variable $rewrite to boole and true
#Judge whether it is legal IP
if ($remote_addr = "192.168.184.10"){		#When the client IP is 192.168.184.10, set the variable value to false without rewriting
    set $rewrite false;
}
#In addition to legal IP, others are illegal IP. Rewrite and jump to the maintenance page
if ($rewrite = true){						#Override when the variable value is true
    rewrite (.+) /weihu.html;				#Override insert / Weihu. After accessing IP HTML, for example 192.168.184.11/weihu.html html
}
location = /weihu.html {
    root /var/www/html;						#Return to / var / www / HTML / Weihu HTML content
}

location / {
    root   html;
    index  index.html index.htm;
}

}

mkdir -p /var/www/html/
echo 'hello weihu!' > /var/www/html/weihu.html
systemctl restart nginx

Browser access
only IP 192.168.184.10 It can be accessed normally, and other addresses are maintenance pages

3,Jump to the new domain name based on the old domain name and add a directory after it

Now visit http://kiki.lic.com, now you need to jump to all the visits under this domain name http://www.lic.com/kiki

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  kiki.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com-access.log;
	#add to
	location /post {
        rewrite (.+) http://www.lic.com/kiki permanent; 		# Here, $1 is the location variable, representing / post
    }
location / {
    root   html;
    index  index.html index.htm;
}

}


mkdir -p /usr/local/nginx/html/kiki/post
systemctl restart nginx.service 

Access with browser
http://kiki.lic.com/post/1.html Jump to http://www.lic.com/kiki/post/1.html

echo 'this is 1.html' > /usr/local/nginx/html/kiki/post/1.html
systemctl restart nginx.service 

4. Jump based on parameter matching

Visit now http://www.lic.com/100-(100|200)-100.html jump to http://www.lic.com Page.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com-access.log  main;
if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
    rewrite (.+) http://www.lic.com permanent;
}

location / {
    root   html;
    index  index.html index.htm;
}

}

systemctl restart nginx

Browser access
http://www.lic.com/100-200-100.html Or http://www.lic.com/100-100-100.html Jump to http://www.lic.com Page.

5. Jump based on all php ending files in the directory

Request access http://www.lic.com/upload/123.php Jump to the home page.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com-access.log  main;

location ~* /upload/.*.php$ {
rewrite (.+) http://www.lic.com permanent;
}

location / {
root html;
index index.html index.htm;
}
}

systemctl restart nginx

Browser access
http://www.lic.com/upload/123.php Jump to http://www.lic.com Page.

6. Jump based on the most common url request

Request access to a specific page, such as http://www.lic.com/abc/123.html Jump to home page

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.lic.com;		#Domain name modification	
	charset utf-8;
	access_log  /var/log/nginx/www.lic.com-access.log  main;
location ~* ^/abc/123.html {
    rewrite (.+) http://www.lic.com permanent;
}

location / {
    root   html;
    index  index.html index.htm;
}

}

systemctl restart nginx


Browser access
http://www.lic.com/abc/123.html Go to www.lic com

Keywords: Operation & Maintenance

Added by mitcho on Thu, 03 Feb 2022 13:10:50 +0200