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

Vue implements multiple selections in the bottom pop-up window

This article example shares the specific code of ...

Detailed explanation of simple snow effect example using JS

Table of contents Preface Main implementation cod...

Vendor Prefix: Why do we need a browser engine prefix?

What is the Vendor Prefix? Vendor prefix—Browser ...

Centos6.9 installation Mysql5.7.18 step record

Installation sequence rpm -ivh mysql-community-co...

Notes on Using Textarea

Why mention textarea specifically? Because the tex...

Nginx external network access intranet site configuration operation

background: The site is separated from the front ...

Summary of twelve methods of Vue value transfer

Table of contents 1. From father to son 2. Son to...

How to position the header at the top using CSS sticky layout

Application scenarios: One of the new requirement...

Vue batch update dom implementation steps

Table of contents Scene Introduction Deep respons...

Collection of 25 fonts used in famous website logos

This article collects the fonts used in the logos...

Detailed explanation of cocoscreater prefab

Table of contents Prefab How to create a prefab T...

JavaScript common statements loop, judgment, string to number

Table of contents 1. switch 2. While Loop 3. Do/W...

Implementation of Grid common layout

No gaps on both sides, gaps between each column w...

Node+express to achieve paging effect

This article shares the specific code of node+exp...