Nginx rewrite regular match rewrite method example

Time:2021-8-24

The rewrite function of nginx supports regular match rewriting, that is, the URL address is temporarily or permanently redirected to a new location, similar to redirection. This feature can be used when the website structure is greatly adjusted. For example, the previous website MP3 resources are accessed with the URL www.site1.org/mp3, but now the MP3 directory on the server has been replaced with the music directory, the rewrite function can be easily realized. Secondly, if site1.org can be forcibly adjusted to www.site1.org, or vice versa. This instruction is located in NGX_ http_ rewrite_ Module module. This paper mainly describes the usage of this instruction and gives a demonstration.

1、 Rewrite instruction syntax description

Syntax: Rewrite regex replacement [flag];
Default:-
Context: server, location, if

If the specified regular expression matches the request URI, the URI changes as specified in the replacement string.
The rewrite instruction is executed in the order in which it appears in the configuration file. Flags can be used to terminate further processing of pseudo instructions.
If the replacement string starts with “http: / /”, “HTTPS: / /”, or “$scheme”, the processing stops and the redirection is returned to the client.

The flag flag is used to control whether to continue checking the subsequent rewrite rules after matching the corresponding rewrite rules
The optional flag parameter can be one of the following:

last
Once matched and rewritten by the current rule, immediately stop checking other rewritten rules, and then re initiate the request through the rewritten rule;

break
Once it is matched and rewritten by the current rule, immediately stop the subsequent rewritten rules, and then continue the subsequent operations by nginx;

redirect
If the replacement string does not start with “http: / /”, “HTTPS: / /” or “$scheme”, use and return 302 temporary redirection;

permanent
Return 301 permanent redirection;

Note: generally, the break flag is used when rewriting in location, or rewriting in if context;

Other instructions

rewrite_log on|off
Whether the rewriting process is recorded in the error log; The default is notice level; The default is off;

return code:
It is used to end the rewrite rule and return the status code for the customer; The status codes that can be used include 204, 400, 402-406, 500-504, etc;

2、 Demonstration of rewrite function based on location context

Native environment
 # more /etc/redhat-release
 CentOS Linux release 7.2.1511 (Core)
 # nginx -v
 nginx version: nginx/1.12.2

Configure nginx
 # vim /etc/nginx/conf.d/rewrite.conf
 server {
  listen 80;
  server_name site1.orag www.site1.org;

  location / {
    root /www/site1.org;
    index index.html index.htm;
  }
 }

 # mkdir -pv /www/site1.org/images
 # echo "This is a rewrite test page.">/www/site1.org/index.html
 # cp /usr/share/backgrounds/gnome/*.jpg /www/site1.org/images/

 # vim /etc/hosts
 192.168.1.175 site1.org
 192.168.1.175 www.site1.org

 # curl http://www.site1.org
 This is a rewrite test page.

 # curl -I https://imgs.developpaper.com/imgs/Waves.jpg
 HTTP/1.1 200 OK
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 03:47:58 GMT
 Content-Type: image/jpeg
 Content-Length: 458818
 Last-Modified: Wed, 01 Nov 2017 03:43:48 GMT
 Connection: keep-alive
 ETag: "59f942f4-70042"
 Accept-Ranges: bytes

Modify the rewrite.conf file and add the rewrite instruction
 location / {
  root /www/site1.org;
  index index.html index.htm;
  rewrite ^/images/(.*)$ /imgs/$1 last;
 }

 # systemctl reload nginx

 # curl -I https://imgs.developpaper.com/imgs/Waves.jpg
 HTTP/1.1 404 Not Found
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 04:02:38 GMT
 Content-Type: text/html
 Content-Length: 169
 Connection: keep-alive

 # mkdir -pv /www/site1.org/imgs

 # mv /www/site1.org/images/Waves.jpg /www/site1.org/imgs/.
 # curl -I https://imgs.developpaper.com/imgs/Waves.jpg
 HTTP/1.1 200 OK
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 04:05:07 GMT
 Content-Type: image/jpeg
 Content-Length: 458818
 Last-Modified: Wed, 01 Nov 2017 03:43:48 GMT
 Connection: keep-alive
 ETag: "59f942f4-70042"
 Accept-Ranges: bytes

 # curl -I  https://imgs.developpaper.com/imgs/Waves.jpg  ##This way you can access
 HTTP/1.1 200 OK
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 04:06:17 GMT
 Content-Type: image/jpeg
 Content-Length: 458818
 Last-Modified: Wed, 01 Nov 2017 03:43:48 GMT
 Connection: keep-alive
 ETag: "59f942f4-70042"
 Accept-Ranges: bytes

Simulate HTTP 500 error caused by rewrite
Make the following modifications to the rewrite.conf file again,

 location / {
  root /www/site1.org;
  index index.html index.htm;
  rewrite ^/images/(.*)$ /imgs/$1 last;
  rewrite ^/imgs/(.*)$ /images/$1 ;
 }

 # systemctl restart nginx
 # curl -I https://imgs.developpaper.com/imgs/Waves.jpg
 HTTP/1.1 500 Internal Server Error
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 05:23:16 GMT
 Content-Type: text/html
 Content-Length: 193
 Connection: close

 # curl -I https://imgs.developpaper.com/imgs/Waves.jpg
 HTTP/1.1 500 Internal Server Error
 Server: nginx/1.12.2
 Date: Wed, 01 Nov 2017 05:23:28 GMT
 Content-Type: text/html
 Content-Length: 193
 Connection: close

Through the above test, it can be seen that 500 errors caused by dead cycle occur.
Official reference examples given by nginx:
 server {
  The... ##rewrite directive is in the server context
 rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
 ##Redirect any file request under the media directory contained in the / download directory to donwload / any / MP3 / any. MP3

 rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;
 ##Redirect any file request in the / download directory containing audio directory to donwload / any / MP3 / any. MP3

 return 403;
  ...
 }

 The location / download / {##rewrite instruction is in the location context
 rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
 ##The last flag should be replaced with break, otherwise nginx will return 500 errors in 10 cycles
 rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra break;
 return 403;
 }

3、 Demonstration of rewrite function based on if condition judgment

# vi /etc/nginx/conf.d/rewrite.conf
  server {
    listen 80;
    server_name site1.orag www.site1.org;

   if ($host != 'www.site1.org' ) {
     rewrite ^/(.*)$ http://www.site1.org/$1 permanent;
    }

  location / { ##Author : Leshami
    root /www/site1.org; ##Blog : http://blog.csdn.net/leshami
    index index.html index.htm;
    rewrite ^/images/(.*)$ /imgs/$1 last;
    rewrite ^/imgs/(.*)$ /images/$1 ;
  }
 }

 # systemctl reload nginx.service

Local test (modify local host file)
 # curl http://site1.org
 <html>## return 301 status code
 <head><title>301 Moved Permanently</title></head>
 <body bgcolor="white">
 <center><h1>301 Moved Permanently</h1></center>
 <hr><center>nginx/1.12.2</center>
 </body>
 </html>

Windows environment test
By modifying the windows machine host file, add the following entry
 192.168.1.175 centos7-router.com
 192.168.1.175 www.centos7-router.com

Open the browser and access through the domain name http://site1.org Will automatically jump to http://www.site1.org (omitted)

4、 Rewrite HTTP to HTTPS

In the case of non whole station HTTPS, some sensitive data need to go through HTTPS, which can also be realized by rewriting

The following example assumes that https://www.site1.org/user The directory contains sensitive information. You can rewrite it as follows

location ^~ /user {
 rewrite ^/ https://www.site1.org$request_uri? permanent;
 }

Total station HTTPS
 server {
  listen 80;
  server_name site1.orag www.site1.org;
  access_log /var/log/nginx/http-access.log;
  error_log /var/log/nginx/http-error.log;

  rewrite ^/ https://www.site1.org$request_uri;
 }

The above demonstration is omitted

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]