Linux system Rewrite and Location jump detailed explanation and example analysis

1. Rewrite explanation

Use global variables provided by nginx or variables set by yourself, combined with regular expressions and flags to achieve URL rewriting and redirection.

(1) Jump scene

Insert picture description here

(2) Jump realization

Insert picture description here

(3) Nginx regular expression
character significance
^ Match the starting position of the input string
$ Match the end position of the input string
* Match the preceding character zero or more times
+ Match the preceding character one or more times
? Match the preceding character zero or one time
. Match all characters except "\n"
\ Mark the following character as a special character or a literal character or a back reference
\d Match pure numbers
{n} Repeat n times
{n,} Repeat n times or more
[c] Matches a single character c
[a-z] Match any one of az lowercase letters
[a-zA-Z0-9] Match all uppercase and lowercase letters or numbers
() The start and end position of the expression
(4) Grammar format
rewrite <regex> <replacement> [flag];
regex :表示正则匹配规则。
replacement :表示跳转后的内容。
flag :表示 rewrite 支持的 flag 标记。
flag标记说明
last :本条规则匹配完成后,继续向下匹配新的location URI规则,一般用在 server 和 if 中。
break :本条规则匹配完成即终止,不再匹配后面的任何规则,一般使用在 location 中。
redirect :返回302临时重定向,浏览器地址会显示跳转后的URL地址。
permanent :返回301永久重定向,浏览器地址栏会显示跳转后的URL地址。

Two, Rewrite experiment

(1) Redirect based on domain name

Now the company's old domain name www.kgc.com has business needs changes, and it needs to be replaced with a new domain name www.benet.com, but the old domain name cannot be abolished, and it needs to be redirected to the new domain name, and the following parameters remain unchanged.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;	#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log  main; #日志修改
	location / {
	#添加域名重定向
        if ($host = 'www.kgc.com'){	 #$host为rewrite全局变量,代表请求主机头字段或主机名
			rewrite ^/(.*)$ http://www.benet.com/$1 permanent;	#$1为正则匹配的内容,即域名后边的字符串
        }
        root   html;
        index  index.html index.htm;
    }
}

echo "IP www.kgc.com www.benet.com" >> /etc/hosts
systemctl restart nginx

浏览器输入模拟访问 http://www.kgc.com/test/1.html(虽然这个请求内容是不存在的)
会跳转到www.benet.com/test/1.html
查看元素可以看到返回301,实现了永久重定向跳转,而且域名后的参数也正常跳转。

Insert picture description here

(2) Access redirect based on client IP

Today, the new version of the company’s business is online, requiring all IPs to access any content to display a fixed maintenance page, and only the company’s IP: 192.168.90.14 can be accessed normally.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;	#日志修改

	#设置是否合法的IP标记
    set $rewrite true;							#设置变量$rewrite,变量值为boole值true
    
    #判断是否为合法IP
	if ($remote_addr = "192.168.90.14"){		#当客户端IP为192.168.90.14时,将变量值设为false,不进行重写
        set $rewrite false;
    }
	
	#除了合法IP,其它都是非法IP,进行重写跳转维护页面
    if ($rewrite = true){						#当变量值为true时,进行重写
        rewrite (.+) /weihu.html;				#重写在访问IP后边插入/weihu.html
    }
    
    location = /weihu.html {
        root /var/www/html;						#网页返回/var/www/html/weihu.html的内容
    }
	
	location / {
        root   html;
        index  index.html index.htm;
    }
}


mkdir -p /var/www/html/
echo "<h1>We are maintaining now</h1>" > /var/www/html/weihu.html
systemctl restart nginx
只有 IP 为 192.168.90.14 能正常访问,其它地址都是维护页面

Three, location explanation

From the function point of view, rewrite and location seem to be a bit similar. Both can achieve redirection. The
main difference is that rewrite is to change the path to obtain resources within the same domain name, while location is to control access or reverse proxy for a type of path, and it can also proxy_pass to other machine.

(1) Location can be roughly divided into three categories:
  • Exact match: location = / {}
  • General match: location / {}
  • Regular match: location ~ / {}
(2) Location commonly used matching rules:
= :进行普通字符精确匹配,也就是完全匹配。 
^~ :表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其它 location。 
~ :区分大小写的匹配。 
~* :不区分大小写的匹配。 
!~ :区分大小写的匹配取非。 
!~* :不区分大小写的匹配取非。
(3) Location priority:
首先精确匹配 =
其次前缀匹配 ^~
其次是按文件中顺序的正则匹配 ~或~*
然后匹配不带任何修饰的前缀匹配
最后是交给 / 通用匹配

Priority instance

  • location = / {}
    = is an exact match /, the host name cannot be followed by any string, such as accessing / and /data, then / matches, /data does not match. For example, location = /abc, only /abc and /abc are matched /Or /abcd does not match. If location /abc, it will match /abc, /abcd/ and /abc/ at the same time.

  • location / {} Because all addresses start with /, this rule will match all requests such as access to / and /data, then / will match, and /data will also match, but if there is a regular expression, it will match the longest character String first match (longest match)

  • location /documents/ {} matches any address that starts with /documents/. After the match is matched, continue to search for other locations. Only when the regular expressions behind other locations do not match, this one will be used

  • location /documents/abc {} matches any
    address starting with /documents/abc . After the match is met, continue to search for other locations. Only when the regular expressions behind other locations do not match, this one will be used

  • location ^~ /images/ {} matches any address starting with /images/, after the match is met, stop searching the regular, use this one

  • location ~* .(gif|jpg|jpeg)$ {} matches all requests ending with gif, jpg, or jpeg. However, all requests for images under /images/ will be processed by location ^~ /images/ because ^~ takes precedence The level is higher, so this rule cannot be reached

  • location /images/abc {} The longest character matches /images/abc, with the lowest priority. If you continue to search for other locations, you will find that ^~ and ~ exist

  • location ~ /images/abc {} matches those starting with /images/abc, the priority is the second, only if location ^~ /images/ is removed, this one will be adopted

  • location /images/abc/1.html {} matches the /images/abc/1.html file. If compared with the regular ~/images/abc/1.html, the regular priority is higher.
    Summary of priorities:

(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (location /)

Four, location experiment

In actual website usage, there are at least three matching rule definitions:

(1) The first required rule
directly matches the root of the website. It is more frequent to visit the homepage of the website through the domain name. Using this will speed up processing, such as the official website.
This is directly forwarded to the back-end application server, or it can be a static homepage

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

(2) The second mandatory rule is to process static file requests, which is the strength of nginx as an http server.
There are two configuration modes, directory matching or suffix matching, choose either one or a combination

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

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

(3) The third rule is a general rule, for example, it is used to forward dynamic requests with .php and .jsp suffixes to the back-end application server.
Non-static file requests are dynamic requests by default.

location / {
    proxy_pass http://tomcat_server;
}

Guess you like

Origin blog.csdn.net/weixin_51468875/article/details/112610104