Nginx Rewrite technology

Nginx Rewrite technology

Rewrite syntax:

rewrite {
    
    规则} {
    
    定向路径} {
    
    重写类型}
rewrite ^/(.*) http://www.test.com/$1 permanent;

Rewrite rewrite type:

Last is equivalent to the [L] mark in Apache, which means that the rewrite
break is complete. After this rule is matched, the match will be terminated, and the following rules will no longer be matched.
Redirect Return 302 temporary redirection, and the browser address will display the redirected URL address
permanent Return 301 permanent redirection, the browser address will display the URL address after the redirection

Rewrite example:

1. When visiting http://106.52.36.65/1024.html, redirect to http://106.52.36.65/index.php?id=1024

location / {
    
    
    rewrite ^/(\d+)\.html$ /index.php?id=$1 redirect;
    #rewrite ^/(\d+)\.html$ /index.php?id=$1 break;
}
curl http://106.52.36.65/1024.html -L

Return result:

C:\Users\v_lysvliu>curl http://106.52.36.65/1024.html -L
<pre>Array
(
    [id] => 1024
)

C:\Users\v_lysvliu>

2. When visiting http://106.52.36.65/home/1024.html, redirect to http://106.52.36.65/index.php?id=1024

location / {
    
    
	rewrite ^/home/(\d+)\.html$ /index.php?id=$1 redirect;
}

3. When visiting http://106.52.36.65/admin/1024.html, redirect to http://106.52.36.65/admin/index.php?id=1024

location / {
    
    
	rewrite ^/(\w+)/(\d+)\.html$ /$1/index.php?id=$2 redirect;
}

4. When visiting http://106.52.36.65/home/12-31-2020.html, redirect to http://106.52.36.65/home/index.php?

id=2020-12-31
location / {
    
    
	rewrite ^/(\w+)/(\d+)-(\d+)-(\d+)\.html$ /$1/index.php?id=$3-$1-$2 redirect;
}
  1. When visiting http://106.52.36.65, redirect to http://www.baidu.com
location / {
    
    
	rewrite .* http://www.baidu.com permanent;
}

6. When visiting http://106.52.36.65:80, redirect to http://106.52.36.65:443

location / {
    
    
	if ($server_port ~* 80) {
    
    
		rewrite .* http://106.52.36.65:443 permanent;
		#rewrite .* http://$host:443 permanent;
	}
}

Guess you like

Origin blog.csdn.net/weixin_39218464/article/details/112723892