Nginx Rewrite (rewrite jump)

1. Overview of Nginx Rewrite

1. Rewrite jump scene

Rewrite function: Use the global variables provided by nginx or the variables set by yourself, combined with regular expressions and tag bits to realize URL rewriting and redirection.
For example: after changing the domain name, it is necessary to keep the old domain name to be able to jump to the new domain name, a certain webpage needs to be redirected to the new page, anti-hotlinking of the website, etc.

rewrite can only be placed in server{}, location{}, if{}, and by default it can only work on the string after the domain name except the passed parameters. For example, http://www.kgc.com/abc/bbs/index.php?a=1&b=2 only rewrites /abc/bbs/index.php.

2. Rewrite jump scene

(1) The URL looks more standardized and reasonable

  • URL: is a specific path/location
  • URI: refers to a collection of objects of the same type/property
  • URN: locate by name

(2) Enterprises will disguise dynamic URL addresses as static addresses to provide services

(3) After the URL is changed to a new domain name, let the old access jump to the new domain name

(4) Some business adjustments on the server side

3. Rewrite jump implementation

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eowXFNXG-1687863267489) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230626223022256.png)]

4. Rewrite the actual scene

4.1 Implementation of Nginx Jump Requirements

(1) Use rewrite for matching jump (such as anti-leech)

(2) Jump after using if to match the global variable (this matching global variable is the global variable of the nginx service itself)

(3) Use location to match and then jump (matched access URL path, location can match local rewriting and cross-server jump)

4.2 Rewrite is placed in the server{}, if{}, location{} segments

location only works on the string after the domain name except the passed parameters

4.3 For domain names or parameter strings

(1) Use if global variable matching
(2) Use proxy_pass reverse proxy

5. nginx regular expression

5.1 Commonly used regular expression metacharacters

character Description^
^ match the beginning of the input string
$ Matches the end of the input string
* Matches the preceding character zero or more times
+ Matches the preceding character one or more times
? Matches the preceding character zero or one time
. matches any single character except "\n"
\ mark the following character as a special character or a literal character or a backreference
\d match pure numbers
{n} repeat n times
{n,} repeat n or more times
[c] matches a single character c
[z-a] Match any of the lowercase letters of az
[z-aA-Z] Match any of az lowercase letters or AZ uppercase letters
() where the expression starts and ends
| or operator

6. Rewrite command

6.1 Rewrite Command Syntax

rewrite [fiag];

regex:regular

replacement: the content after the jump

fiag: flag flag supported by rewrite (judgment)

6.2 flag mark description

mark illustrate features
last It is equivalent to the [L] mark of apache, indicating that the rewrite is completed After this rule is completed, continue to match the new location URL rule downwards, generally or used in server and if
break This rule is terminated when it is matched, and any rule that does not follow the match break is often used under location, similar to last, but it will not re-initiate the processing process, but directly return the processing result
redirect Return 302 temporary redirection, the browser address will display the URL address after the jump, and the crawler will not update the url This mark indicates that the redirect operation will be performed immediately after the current rule matches successfully
permanent Return 301 permanent redirection, the browser address bar will display the redirected URL address, and the crawler will update the URL This tag is similar to redirect, he is a permanent redirect

set: mark indicates that the current rule matches a variable successfully set, and passes the variable to the next rule

6.3 Comparison between last and break

last break
scenes to be used Generally written in server and if Generally used in location
URL matching Does not terminate rewritten url matching Terminate url matching after rewriting
总:从功能看,rewrite和location似乎有点像,都能实现跳转,主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,还可以proxy_pass到其他机器。
rewrite 对访问的域名或者域名内的URL路径地址重写
location对访问的路径做访问控制或者代理转发

Two.location

1. Location classification

1.1 exact match

location = patt {}

1.2 General matching

location patt {}

1.3 regular matching

location ~ patt {}

2. Commonly used expressions for regular matching

mark illustrate
~ Perform a regex match, case sensitive
~* Perform a regex match, case insensitive
!~ Perform a regex match, case-sensitive mismatch
!~* Perform a regex match, case insensitive mismatch
^~ Ordinary character matching, using prefix matching, if the match is successful, no other location will be matched
= Ordinary character exact match, that is, exact match
@ Defines the location of a command, used when targeting internally

3. location priority

(1) First exact match:=

(2) Followed by prefix matching: ^~

(3) Followed by regular matching in order in the file: or *

(4) Then match the prefix match without any modification

(5) Finally, hand over/universal matching

总结:
(1)优先级总结:(location=完整路径)>(location ^~ 路径)>(location~,~*正则顺序)>(location不分起始路径)>(location /)
(2)location匹配:
首先看优先级:精确(=)>前缀(^~)>正则(~,~*)>一般>通用(/)
优先级相同:正则看上下顺序,上面的优先,一般匹配看长度,最长匹配的优先
精确,前缀,正则,一般都没有匹配到,最后再看通用匹配,一般匹配

4. location example

(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 文件,如果和正则location ~ /images/abc/1.html 相比,正则优先级更高

5.实际网站使用中,至少有三个匹配规则定义

5.1第一个必选规则

直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,比如说官网。

可以是一个静态首页,也可以直接转发给后端应用服务器

location = / {

​ root html;

​ index index.html index.htm;

}

5.2第二个必选规则

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

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

5.3第三个规则就是通用规则

比如用来转发带.php、.jsp后缀的动态请求到后端应用服务器

非静态文件请求就默认是动态请求

location / {

​ proxy_pass http://tomcat_server;

}

三.rewrite 实例

1.基于域名的跳转

现在公司旧域名www.kgc.com有业务需求变更,需要使用新域名www.benet.com代替,但是旧域名不能废除,需要跳转到新域名上,而且后面的参数保持不变。
目的:业务变更

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

    location / {
 #添加域名重定向
       #$host为rewrite全局变量,代表请求主机头字段或主机名
        if ($host = 'www.kgc.com'){
#$1为正则匹配的内容,即“域名/”之后的字符串
         rewrite ^/(.*)$ http://www.benet.com/$1 permanent;
        }
        root   html;
        index  index.html index.htm;
 }
echo "192.168.198.13 www.kgc.com www.benet.com" >> /etc/hosts
nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
systemctl restart nginx.service

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

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Cmz8reF6-1687863267490) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627154506688.png)]

访问www.kgc.com域名时跳转到新的域名www.benet.com

跳转之前

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-brtJuBxY-1687863267491) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627154906011.png)]

跳转之后

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-k7jS58Bj-1687863267491) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627154101015.png)]

2.基于客户端 IP 访问跳转

今天公司业务新版本上线,要求所有 IP 访问任何内容都显示一个固定维护页面,只有公司 IP :192.168.198.13访问正常。
目的:需要别人禁止访问或网站维护,需要禁止别人访问

server {
        listen       80;
#域名修改	
        server_name  www.txbb.com;
        charset utf-8;
#日志修改
        access_log  /var/log/www.txbb.com-access.log;
#设置是否合法的IP标记
#设置变量$rewrite,变量值为boole值true(boole就是判断真假
        set $rewrite true;
#判断是否为合法IP
        if ($remote_addr = "192.168.198.13"){
        set $rewrite false;
}
#除了合法IP,其它都是非法IP,进行重写跳转维护页面
#当变量值为true时,进行重写
        if ($rewrite = true){
#将域名后边的路径重写成/weihu.html,例如www.txbb.com/weihu.html
        rewrite (.+) /weihu.html;
}
        location = /weihu.html {
#网页返回/var/www/html/weihu.html的内容
            root   /var/www/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
nginx -t
systemctl restart nginx

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

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Ehcac6Tf-1687863267492) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627174632779.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9m092vYK-1687863267492)(C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627174738912.png)]

3.基于旧域名跳转到新域名后面加目录

现在访问的是 http://bbs.kgc.com/post/,现在需要将这个域名下面的访问都跳转到http://www.kgc.com/bbs/post/

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

        location / {
            root html;
            index  index.html index.htm;
          }
}
mkdir -p /usr/local/nginx/html/bbs/post
echo "this is 1.html"  >> /usr/local/nginx/html/bbs/post/1.html
echo "192.168.198.13 bbs.kgc.com"  >> /etc/hosts
echo "192.168.198.13 ww.kgc.com"  >> /etc/hosts
nginx -t
systemctl restart nginx

使用浏览器访问 http://bbs.kgc.com/post/1.html 跳转到 http://www.kgc.com/bbs/post/1.html

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2GWBTpEz-1687863267492)(C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627183653244.png)]

4.基于参数匹配的跳转

现在访问http://www.kgc.com/100-(100|200)-100.html 跳转到http://www.kgc.com页面。

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;
	
	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

使用浏览器访问 http://www.kgc.com/100-200-100.html 或 http://www.kgc.com/100-100-100.html 跳转到http://www.kgc.com页面。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pk7OqSof-1687863267492)(C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627184044887.png)]

5.基于目录下所有 php 结尾的文件跳转

要求访问 http://www.kgc.com/upload/123.php 跳转到首页。

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

浏览器访问 http://www.kgc.com/upload/123.php 跳转到http://www.kgc.com页面。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Or4Ud3ws-1687863267493)(C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627184322654.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H3hlPpnw-1687863267493)(C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230627184340608.png)]

6.基于最普通一条 url 请求的跳转

要求访问一个具体的页面如 http://www.kgc.com/abc/123.html 跳转到首页

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 ~* ^/abc/123.html {
        rewrite (.+) http://www.kgc.com permanent;
    }
#或者 if ( $request_uri ~* ^/abc/abc.html$){
rewrite (.+) http://www.kgc.com permanent;
}

	location / {
        root   html;
        index  index.html index.htm;
    }
}
systemctl restart nginx

浏览器访问 http://www.kgc.com/abc/123.html 跳转到http://www.kgc.com页面。

在这里插入图片描述
在这里插入图片描述

1.重要:
Rewrite的实际场景,实现方式,flag标记说明,last和break的比较
location的匹配规则,优先级
Rewrite和location的比较
2.遇到的问题
配置文件的细致优化,配置错误
域名映射问题
echo传参未生效

Guess you like

Origin blog.csdn.net/Katie_ff/article/details/131423418