Nginx之Rewrite

1. Common Nginx regular expressions

^:匹配输入字符串的起始位置
$:匹配输入字符串的结束位置
*:匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll”
+:匹配前面的字符一次或者多次。如“ol+”能匹配"ol"及“oll”、"olll",但不能匹配“o”
?:匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,“?”等效于“{
    
    0,1}”
.:匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“{
    
    .\n}”之类的模式
\:将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用,如“\n”匹配一个换行符,而“\$”则匹配“$”
\d:匹配纯数字
{
    
    n}:重复n次
{
    
    n,}:重复n次或更多次
{
    
    n,m}:重复n到m次
[]:定义匹配的字符范围
[c]:匹配单个字符c
[a-z]:匹配a-z小写字母的任意一个
[a-zA-Z0-9]:匹配所有大小写字母或者数字任意一个
():表达式的开始和结束位置
|:或运算符

Two, location classification

1、精准匹配:location = / {
    
    ...}
2、一般匹配:location / {
    
    ...}
3、正则匹配:location ~ / {
    
    ...}

3. Commonly used matching rules for location

=:进行普通字符精确匹配,也就是完全匹配
^~:表示普通字符匹配,使用前缀匹配,如果匹配成功,就不再匹配其他的location
~:区分大小写的匹配
~*:不区分大小写的匹配
!~:区分大小写的匹配取非
!~*:不区分大小写的匹配取非

Fourth, location priority

  • Exact match first =
  • Second prefix match^~
  • The second is regular matching according to the order in the file ~ or ~*
  • Then match the prefix match without any modification
  • Finally, it is handed over/universal matching
    location instance description:
(1)location = / {
    
    }
=为精确匹配 / ,主机名后面不能带任何字符串,比如访问 / 和 /data,则 / 匹配,/data 不匹配
再比如 location = /abc,则只匹配/abc ,/abc/或 /abcd不匹配。若 location  /abc,则即匹配/abc 、/abcd/ 同时也匹配 /abc/。

(2)location / {
    
    }
因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求 比如访问 / 和 /data, 则 / 匹配, /data 也匹配,
但若后面是正则表达式会和最长字符串优先匹配(最长匹配)

(3)location /documents/ {
    
    }
匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索其它 location
只有其它 location后面的正则表达式没有匹配到时,才会采用这一条

(4)location /documents/abc {
    
    }
匹配任何以 /documents/abc 开头的地址,匹配符合以后,还要继续往下搜索其它 location
只有其它 location后面的正则表达式没有匹配到时,才会采用这一条

(5)location ^~ /images/ {
    
    }
匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条

(6)location ~* \.(gif|jpg|jpeg)$ {
    
    }
匹配所有以 gif、jpg或jpeg 结尾的请求
然而,所有请求 /images/ 下的图片会被 location ^~ /images/ 处理,因为 ^~ 的优先级更高,所以到达不了这一条正则

(7)location /images/abc {
    
    }
最长字符匹配到 /images/abc,优先级最低,继续往下搜索其它 location,会发现 ^~ 和 ~ 存在

(8)location ~ /images/abc {
    
    }
匹配以/images/abc 开头的,优先级次之,只有去掉 location ^~ /images/ 才会采用这一条

(9)location /images/abc/1.html {
    
    }
匹配/images/abc/1.html 文件,如果和正则 ~ /images/abc/1.html 相比,正则优先级更高

Priority summary
(location = full path)> (location ^~ full path)> (location ~, ~* regular sequence)> (location part starting path)> (location /)

5. The matching rules used in the actual website have at least three matching rules

#第一个必选规则
直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,比如说官网。
可以是个静态首页,可以直接转发给后端应用服务器
location = / {
    
    
   root  html;
   index index.html index. htm;
}

#第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    
    
    root /webroot/static/;
}

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

#第三个规则就是通用规则,比如用来转发带.php、.jsp后缀的动态请求到后端应用服务器
非静态文件请求就默认是动态请求
location / {
    
    
    proxy_pass http://tomcat_server;
}

Six, rewrite introduction

1. The role of rewrite

The role of rewrite is to use global variables provided by nginx or variables set by yourself, combined with regular expressions and flags to achieve URL rewriting and redirection.
For example: after changing the domain name, you need to keep the old domain name to be able to jump to the new domain name, a webpage changes and need to jump to a new page, website anti-theft chain, etc.,
rewrite can only be placed in server{},location{}, If{}, and the default can only work on the string after the domain name except the passed parameters,
for example, http://www.kgc.com/a/we/index.php?id=1&u=str only for /a/we/index.php is rewritten.

2. Rewrite jump implementation

Nginx: Support URL rewriting through the ngx_http_rewrite_module module, support if condition judgment, but does not support else
jump: jump from one location to another location, the loop can be executed up to 10 times, after exceeding, nginx will return a 500 error
PCRE support: perl Compatible with regular expression grammar rule matching
Rewrite module set instruction: create a new variable and set its value

3. The order of rewrite execution is as follows

  • Execute the rewrite command in the server block.
  • Perform location matching.
  • Execute the rewrite command in the selected location.

4. Rewrite syntax

rewrite <regex> <replacement> [flag]

regex: Represents regular matching rules.
replacement: Indicates the content after the jump.
flag: Indicates the flag flag supported by rewrite.

5. Flag description

ast :本条规则匹配完成后,继续向下匹配新的location URI规则,一般用在 server 和 if 中。
break :本条规则匹配完成即终止,不再匹配后面的任何规则,一般使用在 location 中。
redirect :返回302临时重定向,浏览器地址会显示跳转后的URL地址。
permanent :返回301永久重定向,浏览器地址栏会显示跳转后的URL地址。

To sum up: from the functional point of view, rewrite and location seem to be a bit similar, both can achieve jump. 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. Can proxy_pass to other machines.

Seven, rewrite instance

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, 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;————————日志修改
	location / {
    
    
	#添加域名重定向
        if ($host = 'www.kgc.com'){
    
    ————————————$host为rewrite全局变量,代表请求主机头字段或主机名
			rewrite ^/(.*)$ http://www.benet.com/$1 permanent;	————————$1为正则匹配的内容,即域名后边的字符串
        }
        root   html;
        index  index.html index.htm;
    }
}

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

Browser input simulation visit http://www.kgc.com/test/1.html (this request content does not exist) will jump to www.benet.com/test/1.html, you can see the elements Returning to 301, the permanent redirection is realized, and the parameters after the domain name are also redirected normally
Insert picture description here
Insert picture description here
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. Only the company’s IP: 192.168.241.3 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.241.3"){
    
    ————————————————当客户端IP为192.168.80.10时,将变量值设为false,不进行重写
        set $rewrite false;
    }
	#除了合法IP,其它都是非法IP,进行重写跳转维护页面
    if ($rewrite = true){
    
    ——————————————————当变量值为true时,进行重写
        rewrite (.+) /weihu.html;————————————重写在访问IP后边插入/weihu.html,例如192.168.241.3/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>this is test</h1>" > /var/www/html/weihu.html

systemctl restart nginx

只有 IP 为 192.168.241.3 能正常访问,其它地址都是维护页面

Insert picture description here
The IP address of 192.168.241.3 can be accessed normally:
Insert picture description here
other IP addresses can access:
Insert picture description here

3. Based on the old domain name, jump to the new domain name and add a directory

Now you are visiting http://bbs.kgc.com, now you need to redirect all visits under this domain name to http://www.kgc.com/bbs

vim /usr/local/nginx/conf/nginx.conf
server {
    
    
	listen       80;
	server_name  bbs.kgc.com;——————————域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;————————日志修改
	location /post {
    
    ——————————添加域名重定向
      rewrite (.+) http://www.kgc.com/bbs$1 permanent;	————————这里的$1为位置变量,代表/post
        }
    location / {
    
    
        root   html;
        index  index.html index.htm;
    }
}

mkdir -p /usr/local/nginx/html/bbs
echo "this is test.html"  >> /usr/local/nginx/html/bbs/1.html
echo "192.168.241.3 bbs.kgc.com"  >> /etc/hosts
systemctl restart nginx
使用浏览器访问 http://bbs.kgc.com/post/1.html 跳转到 http://www.kgc.com/bbs/post/1.html

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

4. Jump based on parameter matching

Now visit http://www.kgc.com/100-(100|200)-100.html to jump to http://www.kgc.com page.

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;
	location ~ /100-(100|200)-(\d+).html$ {
    
    
	#if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
    
    
        rewrite (.+) http://www.kgc.com permanent;
    }
	location / {
    
    
        root   html;
        index  index.html index.htm;
    }
}

systemctl restart nginx

Use a browser to visit http://www.kgc.com/100-200-100.html or http://www.kgc.com/100-100-100.html to jump to http://www.kgc. com page.
Insert picture description here
Insert picture description here
Insert picture description here

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

Request to visit http://www.kgc.com/upload/123.php to jump to the homepage.

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;
	location ~* /upload/.*\.php$ {
    
    
        rewrite (.+) http://www.kgc.com permanent;
    }
	location / {
    
    
        root   html;
        index  index.html index.htm;
    }
}

systemctl restart nginx

The browser visits http://www.kgc.com/upload/123.php to jump to the http://www.kgc.com page.
Insert picture description here
Insert picture description here
Insert picture description here

6. Jump based on the most common URL request

Request to visit a specific page such as http://www.kgc.com/abc/123.html to jump to the homepage

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 ~* ^/abc/123.html {
    
    
        rewrite (.+) http://www.kgc.com permanent;
    }
	location / {
    
    
        root   html;
        index  index.html index.htm;
    }
}

systemctl restart nginx

Browser visit http://www.kgc.com/abc/123.html to jump to http://www.kgc.com page.
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51432789/article/details/112604029