Detailed introduction to Nginx-rewrite module

Preface

Now Nginx has become the first choice of many companies as a front-end reverse proxy (proxy pass) server. In actual work, we often encounter many jump (rewrite URL) requirements. For example, after changing the domain name, you need to keep the old domain name able to jump to the new domain name, a certain webpage changes and you need to jump to a new page, the website needs to be protected from hotlinking, etc. If you use the Apache server in the backend, although it can also do jumps and the rule base is also very powerful, using Nginx to jump will be more efficient.

1. Overview of Nginx-rewrite module

From a functional point of view, rewrite and location seem to be similar, both can achieve jumps. The main difference is that rewrite changes the path to obtain resources within the same domain name, while location controls access or reverse proxy to a class of paths, and can also proxy_pass to other machines.

  • rewrite: Rewrite the visited domain name or the URL path address within the domain name
  • location: perform access control or proxy forwarding on the access path

1. rewrite scenario

  • Adjust the URL that users browse to look more standardized and meet the requirements of development and product personnel.
  • In order to allow search engines to search website content and provide better user experience, companies will disguise dynamic URL addresses as static addresses to provide services.
  • After the URL is changed to a new domain name, access from the old domain name will jump to access from the new domain name. For example, visiting JD.com’s 360buy.com will jump to jd.com.
  • Adjustment of certain services on the server side, such as URL adjustment based on special variables, directories, and client information, etc.

2. rewrite implementation

  • Nginx supports URL rewriting and if conditional judgment through the ngx_http_rewrite_module module, but does not support else.
  • This module requires PCRE support. PCRE support should be specified when compiling Nginx. It is already installed by default. Redirect according to relevant variables and select different configurations to jump from one location to another. However, such a loop can be executed up to 10 times. If it exceeds Nginx will return a 500 error.
  • PCRE support: perl compatible regular expression syntax rule matching
  • At the same time, the rewriting module includes the set directive to create new variables and set their values, which is very useful in some situations, such as recording condition identifiers, passing parameters to other locations, recording what was done, etc.
  • The rewrite function is to use the global variables provided by Nginx or the variables set by yourself, combined with regular expressions and flags to implement URL rewriting and redirection. For example: after changing the domain name, the old domain name needs to be able to jump to the new domain name, a certain web page changes and needs to jump to a new page, the website needs to be protected from hot links, etc.

Insert image description here

3. rewrite execution sequence

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

4. Grammar format

rewrite <regex> <replacement> [flag];
  • regex: represents regular matching rules.
  • replacement: represents the content after the jump.
  • flag: Indicates the flag mark supported by rewrite.

flag description :

  • last: After the matching of this rule is completed, the rewritten url matching will not be terminated. It is generally used in server and if.
  • break: This rule is terminated when the matching is completed. It terminates the rewritten url matching. It is generally used in location.
  • redirect: Returns a 302 temporary redirect, and the browser address will display the URL address after the jump.
  • permanent: Returns 301 permanent redirect, and the browser address bar will display the URL address after the jump.

2. Rewrite example

1. Jump based on domain name

Now the company's old domain name www.kgc.com has changed its business needs and needs to be replaced by the new domain name www.benet.com. However, the old domain name cannot be abolished and needs to be jumped to the new domain name, and the subsequent 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.80.10 www.kgc.com www.benet.com" >> /etc/hosts
systemctl restart nginx

The browser inputs a simulated access to http://www.kgc.com/test/1.html (although the content of this request does not exist) and
it will jump to www.benet.com/test/1.html. You can see the elements by viewing After returning 301, a permanent redirection jump is achieved, and the parameters after the domain name also jump normally.
Insert image description here
Insert image description here

2. Access jump based on client IP

Today, a new version of the company's business is online, which requires all IPs to display a fixed maintenance page when accessing any content. Only the company's IP: 192.168.80.10 has normal access.

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.80.10"){		#当客户端IP为192.168.80.10时,将变量值设为false,不进行重写
        set $rewrite false;
    }
	#除了合法IP,其它都是非法IP,进行重写跳转维护页面
    if ($rewrite = true){						#当变量值为true时,进行重写
        rewrite (.+) /weihu.html;				#将域名后边的路径重写成/weihu.html后转发,例如www.kgc.com/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

Only the IP of 192.168.80.10 can be accessed normally. Other addresses are maintenance pages.
If rewrite (.+) /weihu.html; is replaced by rewrite (.+) /weihu.html permanent;, if it is not accessed by the host of 192.168.80.10 This will cause the browser to modify the requested URL to http://www.kgc.com/weihu.html and then request access. This will enter an infinite loop of rewriting, and the access request will be rewritten to http://www. .kgc.com/weihu.html Request access

Insert image description here

Insert image description here

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

The current visit is http://bbs.kgc.com/post/. Now we need to jump all visits under this domain name to http://www.kgc.com/bbs/post/

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


mkdir -p /var/www/bbs/post
echo "this is 1.html"  >> /var/www/bbs/post/1.html
echo "192.168.80.10 bbs.kgc.com"  >> /etc/hosts
systemctl restart nginx

Use a browser to visit http://bbs.kgc.com/post/1.html and jump to http://www.kgc.com/bbs/post/1.html
Insert image description here
Insert image description here

4. Jump based on parameter matching

Now visit http://www.kgc.com/100-(100|200)-100.html to jump to the 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;
	
	if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
        rewrite (.+) http://www.kgc.com permanent;
    }

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

  • $request_uri: The original URI containing the request parameters, excluding the host name, such as: /abc/bbs/index.php in http://www.kgc.com/abc/bbs/index.html?a=1&b=2 ?a=1&b=2
  • $uri: This variable refers to the current request URI, which does not include any parameters, such as:/abc/bbs/index.html
  • documenturi: give document_uri: givedocumentur i : Same as uri, this variable refers to the current request URI, excluding any passed parameters, such as:/abc/bbs/index.html

systemctl restart nginx

Use your 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 image description here
Insert image description here

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

It is required 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

Insert image description here
Insert image description here

6. Jump based on the most common url request

Request access to a specific page such as http://www.kgc.com/abc/123.html Jump to the home 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 ~* ^/abc/123.html {
        rewrite (.+) http://www.kgc.com permanent;
    }

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

systemctl restart nginx

Visit http://www.kgc.com/abc/123.html with the browser and jump to http://www.kgc.com page.
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/m0_74412260/article/details/131031179