Nginx rewrite regular matching rewriting method example

Nginx rewrite regular matching rewriting method example

Nginx's rewrite function supports regular matching rewriting, which temporarily or permanently redirects the URL address to a new location, similar to redirection. This feature is useful when major adjustments are made to the website structure. For example, the website's mp3 resources were previously accessed using the URL www.site1.org/mp3, but now the mp3 directory on the server has been replaced by the music directory. In this case, the rewrite function can be easily implemented. Secondly, you can force site1.org to be adjusted to www.site1.org, and vice versa. This directive is located in the ngx_http_rewrite_module module. This article mainly describes the usage of this instruction and gives a demonstration.

1. Rewrite command syntax description

Syntax: rewrite regex replacement [flag];
default: -
Context: server, location, if

If the specified regular expression matches the request URI, the URI is changed as specified in the replacement string.
The rewrite directives are executed sequentially in the order they appear in the configuration file. A flag can be used to terminate further processing of a directive.
If the replacement string begins with "http://", "https://", or "$scheme", processing stops and a redirect is returned to the client.

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

last
Once the request is matched and rewritten by the current rule, it will immediately stop checking other subsequent rewrite rules, and then re-initiate the request using the rewritten rule.

break
Once the current rule matches and rewrites the content, the subsequent rewrite rules are stopped immediately, and nginx continues to perform subsequent operations.

redirect
If the replacement string does not start with "http://", "https://" or "$scheme", it is used, returning a 302 temporary redirect;

permanent
Return a 301 permanent redirect;

Note: Generally, the break flag is used when rewrite is written in location, or rewrite is written in the if context;

Other instructions

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

return code:
Used to end the rewrite rule and return a status code to the client; the available status codes include 204, 400, 402-406, 500-504, etc.

2. Demonstration of rewrite function based on location context

Local 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 upload/2022/web/Waves.
 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 directive location / {
  root /www/site1.org;
  index index.html index.htm;
  rewrite ^/images/(.*)$ /imgs/$1 last;
 }

 # systemctl reload nginx

 # curl -I upload/2022/web/Waves.
 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 upload/2022/web/Waves.
 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 upload/2022/web/Waves. ##This method 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

To simulate the http 500 error caused by rewrite, modify the rewrite.conf file as follows:

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

 # systemctl restart nginx
 # curl -I upload/2022/web/Waves.
 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 upload/2022/web/Waves.
 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

The above test shows that a 500 error is caused by an infinite loop.
Reference examples provided by Nginx:
 server {
  ... ##rewrite directive is located in the server context rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
 ##Redirect any file request in the /download directory that contains the media directory to donwload/any/mp3/any.mp3

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

 return 403;
  ...
 }

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

3. Demonstration of rewrite function based on if condition

 # 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 After 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 http://site1.org through the domain name, and it will automatically jump to http://www.site1.org (demonstration omitted)

4. Rewrite http to https

When the entire site is not https, some sensitive data needs to go through https, which can also be achieved through rewrite

In the following example, assuming that the directory https://www.site1.org/user contains sensitive information, it can be rewritten as follows

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

The whole site is 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 briefly

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of Nginx's rewrite module
  • Nginx URL rewriting mechanism principle and usage examples
  • Detailed explanation of location and rewrite usage in nginx
  • How to redirect URL using nginx rewrite
  • Detailed explanation of nginx rewrite and location according to URL parameters
  • Nginx rewrite rewrite basics and examples sharing
  • Nginx Rewrite rules and usage introduction and skills examples
  • nginx rewrite pseudo-static configuration parameters and usage examples
  • Analysis of nginx rewrite function usage scenarios

<<:  Data constraint examples based on MySQL database and introduction to five integrity constraints

>>:  Implementation of React configuration sub-routing

Recommend

Introduction to the B-Tree Insertion Process

In the previous article https://www.jb51.net/arti...

Detailed explanation of MySQL's FreeList mechanism

1. Introduction After MySQL is started, BufferPoo...

Detailed explanation of MySQL delayed replication library method

Simply put, delayed replication is to set a fixed...

Detailed explanation of nginx-naxsi whitelist rules

Whitelist rule syntax: BasicRule wl:ID [negative]...

How to modify port 3389 of Windows server 2008 R2 remote desktop

The default port number of the Windows server rem...

Implementation of Nginx load balancing cluster

(1) Experimental environment youxi1 192.168.5.101...

How to deploy Tencent Cloud Server from scratch

Since this is my first post, if there are any mis...

Summary of several MySQL installation methods and configuration issues

1. MySQL rpm package installation # Download the ...

Develop calculator example code using native javascript

The main function of a calculator is to perform n...

Improvements to the web server to improve website performance

<br />In the first section of this series, w...