Nginx location and rewrite

1. Common Nginx regular expressions

Insert picture description here

Two, location

1. Location can be roughly divided into three categories

Exact match: location = / {}
General match: location / {}
Regular match: location ~ / {}

2. Commonly used matching rules for location:

=: Perform an exact match of ordinary characters, that is, a complete match.
^~: Indicates that common characters are matched. Use prefix matching. If the match is successful, no other locations will be matched.
~: Case-sensitive matching.
~*: Case-insensitive matching.
!~: Case-sensitive match negation.
!~*: Case-insensitive matching negation.

3. Location priority:

First, an exact match =
Second prefix match ^ ~
followed by the sequential positive matching file or *
then matching prefix match without any modification
and finally to / generic matches

4. Location example description:

Insert picture description here

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

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 the 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/;
}

The second mandatory rule
handles 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 is a
general rule, 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

The rewrite 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.lic.com/a/we/index.php?id=1&u=str only rewrites /a/we/index.php.

1. 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

2. 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

3. Rewrite syntax format

Syntax rewrite;
regex: indicates the regular matching rule
replacement: indicates the content after the jump
flag: indicates the flag tag supported by rewrite

4. Flag description

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

echo "192.168.221.80 www.abc.com www.def.com" >> /etc/hosts

mkdir -p /var/log/nginx
systemctl restart nginx.service

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, and only the company’s IP: 192.168.221.88 can be accessed normally.

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.abc.com;
	charset utf-8;
	access_log  /var/log/nginx/www.abc.com.access.log;

	#设置是否合法的IP标记;设置变量$rewrite,变量值为boole值true
    set $rewrite true;
    #判断是否为合法IP;当客户端IP为192.168.221.88时,将变量值设为false,不进行重写
    if ($remote_addr = "192.168.221.88"){
        set $rewrite false;
    }
	#除了合法IP,其它都是非法IP,进行重写跳转维护页面
	#当变量值为true时,进行重写
    if ($rewrite = true){
        #重写在访问IP后边插入/weihu.html,例如192.168.221.80/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 'weihu!' > /var/www/html/weihu.html
systemctl restart nginx

Insert picture description here

Insert picture description here
Insert picture description here
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://def.abc.com, now you need to redirect all visits under this domain name to http://www.abc.com/def

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

mkdir -p /usr/local/nginx/html/def/post
echo 'this is 1.html' > /usr/local/nginx/html/def/post/1.html
 echo "192.168.221.80 def.abc.com www.abc.com" > /etc/hosts
 systemctl restart nginx.service 

访问http://def.abc.com/post/1.html跳转到http://www.abc.com/def/post/1.html

Insert picture description here
Insert picture description hereInsert picture description here

4. Jump based on parameter matching

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

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.abc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.abc.com-access.log;
	
	if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
        rewrite (.+) http://www.abc.com permanent;
    }

	location / {
        root   html;
        index  index.html index.htm;
    }
}
echo "192.168.221.80 www.abc.com" >> /etc/hosts
systemctl restart nginx

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

Insert picture description here
Insert picture description here

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

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

vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.abc.com;
	charset utf-8;
	access_log  /var/log/nginx/www.abc.com.access.log;
	
location ~* /upload/.*\.php$ {
    rewrite (.+) http://www.abc.com permanent;
}

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

echo "192.168.221.80 www.abc.com" >> /etc/hosts
systemctl restart nginx


访问http://www.abc.com/upload/123.php跳转到http://www.abc.com页面

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/s15212790607/article/details/115349218