Location matching and rewrite jump in Nginx

Location matching and rewrite jump in Nginx

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

1.location can be roughly divided into three categories

  • Exact match: location = / {…}
  • General match: location / {...}
  • Regular match: location ~ / {…}

2. Common matching rules for location:

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

3.location priority:

  1. Exact match first =
  2. Secondly, the prefix matches ^~
  3. Followed by the order of the file being matched or *
  4. Then match the prefix match without any modification
  5. Finally, it is handed over / general matching

4. Location example 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 相比,正则优先级更高

优先级总结:
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (location /)

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

The first mandatory rule

It directly matches the root of the website. It is more frequent to access the homepage of the website through the domain name. Using this will speed up the processing. For example, the official website can be a static homepage, or it can be directly forwarded to the back-end application server.

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

The second mandatory rule

Processing 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 of them or use them together

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

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

The third rule

General rules, such as forwarding 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;
}

Three, Rewrite overview

1. Rewrite jump scene

1) Adjust the URL that users browse, which looks more standardized and meets the needs of developers and product personnel

2) In order to allow search engines to search for website content and better user experience, companies 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 visits jump to the new domain name. For example, when you visit 360buy.com on JD.com, you will be redirected to jd.com.

4) Some business adjustments on the server, such as URL adjustments based on special variables, directories, and client information

2.Rewrite function

Its function is to use global variables provided by nginx or variables set by yourself, combined with regular expressions and tags to achieve URL rewriting and redirection.
For example: after changing the domain name, the old domain name needs to be able to be transferred to the new domain name, a certain webpage needs to be redirected to a new page after a change, the website anti-theft chain, etc. needs.

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

3. Rewrite jump implementation

Nginx: Support URL rewriting through the ngx_http_rewrite_module module, support if condition judgment, but 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 new variables and assign values ​​to them

4. Rewrite execution order

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

5.rewrite syntax format

语法rewrite<regex><replacement><flag>;
regex:表示正则匹配规则
replacement:表示跳转后的内容
flag:表示rewrite支持的flag标记

6.flag description

last: After this rule is matched, continue to match the new location URI rule downwards, generally used in server and if.
break: This rule will be terminated when the matching is completed, and will no longer match any subsequent rules. It is generally used in location.
redirect: Return to a 302 temporary redirect, the browser address will display the redirected URL address.
permanent: Return to 301 permanent redirection, and the URL address after the redirection will be displayed in the address bar of the browser.

Four, rewrite example

1. Redirect based on domain name

Now the company’s old domain name www.mhh.com has business needs changes and needs to be replaced with a new domain name www.accp.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.mhh.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.mhh.com.access.log;		#日志修改
	location / {
	#添加域名重定向
        if ($host = 'www.mhh.com'){						            #$host为rewrite全局变量,代表请求主机头字段或主机名
			rewrite ^/(.*)$ http://www.accp.com/$1 permanent;		#$1为正则匹配的内容,即域名后边的字符串
        }
        root   html;
        index  index.html index.htm;
    }
}

Insert picture description here

Insert picture description here

[root@localhost ~]#mkdir -p /var/log/nginx
[root@localhost ~]#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
[root@localhost ~]#vim /usr/local/nginx/conf/nginx.conf
[root@localhost ~]#systemctl restart nginx.service 
[root@localhost ~]#echo "192.168.2.7 www.mhh.com www.accp.com" >> /etc/hosts
[root@localhost ~]#cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.2.7 www.mhh.com www.accp.com

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.2.7 can access normally.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.mhh.com;		#域名修改	
	charset utf-8; #设置字符集
	access_log  /var/log/nginx/www.mhh.com-access.log  main;		#日志修改

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

Insert picture description here

Insert picture description here

Browser access
Only IP 192.168.2.7 can be accessed normally, other addresses are maintenance pages

Insert picture description here

The firewall must be turned off, otherwise access errors will occur

[root@localhost ~]#systemctl stop firewalld
[root@localhost ~]#systemctl disable firewalld
[root@localhost ~]#setenforce 0

Insert picture description here

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

It is required to visit http://www.mhh.com, now it is necessary to redirect all visits under this domain name to http://www.accp.com/test

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

Insert picture description here

Insert picture description here

Use a browser to visit
http://www.mhh.com/post/1.html to jump to http://www.accp.com/test/post/1.html

Insert picture description here

4. Jump based on parameter matching

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

 vim /usr/local/nginx/conf/nginx.conf
 server {
        listen       80;
        server_name  www.mhh.com;    #修改域名

        #charset koi8-r;

        access_log  /var/log/nginx/www.mhh.com-access.log;

        if ($request_uri ~ ^/100-(100|200)-(\d+)\.html$){   #设置正则匹配
            rewrite (.*) http://www.mhh.com permanent;     #设置重写
        }
        location / {
            root   html;
            index  index.html index.htm;
        }


systemctl restart nginx.service 

Insert picture description here

Browser visit http://www.mhh.com/100-200-100.html or http://www.mhh.com/100-100-100.html to jump to http://www.mhh.com page.

Insert picture description here

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

Request to visit http://www.mhh.com/upload/123.php Jump to the homepage

vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  www.mhh.com;

        #charset utf-8;

        access_log  /var/log/nginx/www.mhh.com-access.log;

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

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


systemctl restart nginx.service 

Browser visit http://www.mhh.com/upload/123.php to jump to http://www.mhh.com homepage

Insert picture description here

6. Jump based on the most common url request

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

vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  www.mhh.com;

        #charset utf-8;

        access_log  /var/log/nginx/www.mhh.com-access.log;

        location ~* /abc/123.html {
           rewrite (.+) http://www.mhh.com permanent;
        }

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


systemctl restart nginx.service 

Insert picture description here

Browser visit http://www.mhh.com/abc/123.html to jump to http://www.mhh.com

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35456705/article/details/113486088