Implementation of Nginx forwarding matching rules

Implementation of Nginx forwarding matching rules

1. Regular expression matching

  • ~ for case-sensitive matching
  • ~* is case-insensitive matching
  • !~ and !~* are case-sensitive and case-insensitive matches respectively.

2. File and Directory Matching

  • -f and !-f are used to determine whether a file exists
  • -d and !-d are used to determine whether a directory exists
  • -e and !-e are used to determine whether a file or directory exists
  • -x and !-x are used to determine whether the file is executable

three. The last parameter of the rewrite command is the flag tag, which has

  • last is equivalent to the [L] flag in Apache, which means rewrite.
  • break After this rule is matched, the matching is terminated and the following rules will no longer be matched.
  • redirect returns a 302 temporary redirect, and the browser address will display the URL after the jump.
  • permanent returns a 301 permanent redirect, and the browser address will display the URL after the jump.

Use last and break to rewrite the URI without changing the browser address bar.

There are subtle differences between the two. When using the alias directive, you must use the last marker; when using the proxy_pass directive, you need to use the break marker. After the execution of this rewrite rule, the last tag will re-initiate a request to the server{......} tag where it is located, and the break tag will terminate the matching after the matching of this rule is completed.

For example: if we redirect URL/photo/123456 to /path/to/photo/12/1234/123456.png

rewrite "/photo/([0-9]{2})([0-9]{2})([0-9]{2})" 
rewrite "/path/to/photo/$1/$1$2/$1$2$3.png";

4. NginxRewrite rule related instructions

1. break instruction

Usage environment: server, location, if
The purpose of this directive is to complete the current rule set and no longer process the rewrite directive.

2. if instruction

Usage environment: server, location
This instruction is used to check whether a condition is met. If the condition is met, the statements in the curly braces are executed. The If directive does not support nesting, multiple conditional && and || processing.

3. return instruction

Syntax: returncode
Usage environment: server, location, if
This instruction is used to end the execution of the rule and return a status code to the client.
Example: If the accessed URL ends with ".sh" or ".bash", a 403 status code is returned

location ~ .*\.(sh|bash)?$
{
 return 403;
}

4. rewrite directive

Syntax: rewriteregex replacement flag
Usage environment: server, location, if
This directive redirects a URI based on an expression, or modifies a string. Directives are executed in the order in which they appear in the configuration file. Note that rewrite expressions only work with relative paths. If you want to match hostnames, you should use an if statement, like this:

if( $host ~* www\.(.*) )
{
 set $host_without_www $1;
 rewrite ^(.*)$ http://$host_without_www$1permanent;
}

5. Set command

Syntax: setvariable value;
Default value: none
Usage environment: server, location, if
This instruction is used to define a variable and assign a value to the variable. The value of a variable can be text, a variable, or a combination of text and variables.

set$varname "hello world";

6. Uninitialized_variable_warn directive

Syntax: uninitialized_variable_warnon|off
Usage environment: http, server, location, if
This command is used to turn on and off the warning message of uninitialized variables. The default value is on.

five. Nginx Rewrite rule writing example

1. When the accessed file or directory does not exist, redirect to an HTML file

if( !-e $request_filename )
{
 rewrite ^/(.*)$ index.htmllast;
}

2. Directory swap /123456/xxxx ====> /xxxx?id=123456

rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;

3. If the client is using IE browser, redirect to the /ie directory

if( $http_user_agent ~ MSIE)
{
 rewrite ^(.*)$ /ie/$1 break;
}

4. Prohibit access to multiple directories

location ~ ^/(cron|templates)/
{
 deny all;
 break;
}

5. Prohibit access to files starting with /data

location ~ ^/data
{
 deny all;
}

6. Prohibit access to files with .sh, .flv, .mp3 as file extensions

location ~ .*\.(sh|flv|mp3)$
{
 return 403;
}

7. Set the browser cache time for certain types of files

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
 expires 30d;
}
location ~ .*\.(js|css)$
{
 expires 1h;
}

8. Set expiration time for favicon.ico and robots.txt

Here, favicon.ico is 99 days, robots.txt is 7 days, and 404 error logs are not recorded.

location ~(favicon.ico) {
 log_not_found off;
 expires 99d;
 break;
}
location ~(robots.txt) {
 log_not_found off;
 expires 7d;
 break;
}

9. Set the expiration time of a file; here it is 600 seconds, and the access log is not recorded

location ^~ /html/scripts/loadhead_1.js {
 access_log off;
 root /opt/lampp/htdocs/web;
 expires 600;
 break;
}

10. Anti-hotlinking of files and set expiration time

The return412 here is a custom http status code, the default is 403, which is convenient for finding the correct hotlink request

rewrite ^/ http: //img.linuxidc.net/leech.gif; //Display an anti-leech image access_log off; //Do not record access logs to reduce pressure expires 3d //Browser cache of all files for 3 days location ~*^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
 valid_referers none blocked *.linuxidc.com*.linuxidc.net localhost 208.97.167.194;
if ($invalid_referer) {
  rewrite ^/ upload/2022/web/leech.gif;
  return 412;
  break;
}
access_log off;
root /opt/lampp/htdocs/web;
expires 3d;
break;
}

11. Only allow fixed IP to access the website and add a password

root /opt/htdocs/www;
allow 208.97.167.194; 
allow 222.33.1.2; 
allow 231.152.49.4;
deny all;
auth_basic "C1G_ADMIN";
auth_basic_user_file htpasswd;

12. Convert files in multiple directories into one file to enhance SEO effect

/job-123-456-789.html points to /job/123/456/789.html

rewrite^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;

13. Redirect when files and directories do not exist:

if (!-e $request_filename) {
 proxy_pass http://127.0.0.1;
}

14. Point a folder in the root directory to the second-level directory

For example, /shanghaijob/ points to /area/shanghai/

If you change last to permanent, the browser address bar will show /location/shanghai/

rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;

The problem with the above example is that it will not match when accessing /shanghai

rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;

In this way, /shanghai can also be accessed, but the relative links in the page cannot be used.

For example, if the real address of ./list_1.html is /area/shanghia/list_1.html , it will become /list_1.html , making it inaccessible.

Then I add automatic jump, but it doesn't work.

(-d $request_filename) It has a condition that it must be a real directory, but my rewrite is not, so it has no effect

if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/permanent;
}

It's easy to handle after knowing the reason. Let me jump manually.

rewrite ^/([0-9a-z]+)job$ /$1job/permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;

15. Domain jump

server{
 listen 80;
 server_name jump.linuxidc.com;
 index index.html index.htm index.php;
 root /opt/lampp/htdocs/www;
 rewrite ^/ http://www.linuxidc.com/;
 access_log off;
}

16. Multi-domain redirection

server_name www.linuxidc.comwww.linuxidc.net;
index index.html index.htm index.php;
root /opt/lampp/htdocs;
if ($host ~ "linuxidc\.net") {
 rewrite ^(.*) http://www.linuxidc.com$1permanent;
}

6. nginx global variables

arg_PARAMETER #This variable contains the value of the variable PARAMETER in the GET request, if any.
args #This variable is equal to the parameters in the request line (GET request), such as: foo=123&bar=blahblah;
binary_remote_addr #Binary client address.
body_bytes_sent #The number of body bytes sent in response. This data is accurate even if the connection is lost.
content_length #Content-length field in the request header.
content_type #Content-Type field in the request header.
cookie_COOKIE #The value of the cookie COOKIE variable document_root #The value specified in the root directive of the current request.
document_uri #Same as uri.
host #Request host header field, otherwise the server name.
hostname #Set to themachine's hostname as returned by gethostname
http_HEADER
is_args #If there is an args parameter, this variable is equal to "?", otherwise it is equal to "", an empty value.
http_user_agent #Client agent information http_cookie #Client cookie information limit_rate #This variable can limit the connection rate.
query_string #Same as args.
request_body_file #The temporary file name of the client request body information.
request_method #The action requested by the client, usually GET or POST.
remote_addr #Client IP address.
remote_port #Client port.
remote_user #The user name that has been verified by the Auth Basic Module.
request_completion #If the request is completed, set to OK. When the request is not completed or if the request is not the last one in the request chain, it is empty.
request_method #GET or POST
request_filename #The file path of the current request, generated by the root or alias directive and the URI request.
request_uri #The original URI containing the request parameters, without the host name, such as: "/foo/bar.php?arg=baz". Cannot be modified.
scheme #HTTP method (such as http, https).
server_protocol #The protocol used in the request, usually HTTP/1.0 or HTTP/1.1.
server_addr #Server address. This value can be determined after completing a system call.
server_name #Server name.
server_port #The port number through which the request arrives on the server.

7. Correspondence between Apache and Nginx rules

Apache's RewriteCond corresponds to Nginx's if
Apache's RewriteRule corresponds to Nginx's rewrite
Apache's [R] corresponds to Nginx's redirect
Apache's [P] corresponds to Nginx's last
Apache's [R,L] corresponds to Nginx's redirect
Apache's [P,L] corresponds to Nginx's last
Apache's [PT,L] corresponds to Nginx's last

For example: allow the specified domain name to access this site, and all other domain names will be redirected to www.jb51.net

Apache:

RewriteCond %{HTTP_HOST} !^(.*?)\.aaa\.com$[NC]
RewriteCond %{HTTP_HOST} !^localhost$ 
RewriteCond %{HTTP_HOST}!^192\.168\.0\.(.*?)$
RewriteRule ^/(.*)$ //www.jb51.net[R,L]

Nginx filtering example:

if( $host ~* ^(.*)\.aaa\.com$ )
{
 set $allowHost '1';
}
if( $host ~* ^localhost )
{
 set $allowHost '1';
}
if( $host ~* ^192\.168\.1\.(.*?)$ )
{
 set $allowHost '1';
}
if( $allowHost !~ '1' )
{
 rewrite ^/(.*)$ //www.jb51.netredirect ;
}

Summarize

Back-end development is a profession that is closest to a full-stack job. If the front-end is not enough, the back-end can write page JS on top. It doesn’t matter if there is no operation and maintenance, the back-end will maintain the server. In short, a good back-end is able to cover all aspects.

This is the end of this article about the implementation of Nginx forwarding matching rules. For more relevant Nginx forwarding matching rules, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Nginx location matching rules
  • Nginx rewrite regular matching rewriting method example
  • Nginx Location directive URI matching rules detailed summary
  • Nginx location matching rule example
  • How to match multiple conditions using nginx
  • A brief summary of nginx matching rules (recommended)
  • Detailed explanation of Nginx's various matching methods

<<:  jQuery implements font size adjustment case

>>:  Detailed steps to install mysql 8.0.18-winx64 on win10

Recommend

MySQL 5.7.20 installation and configuration method graphic tutorial (win10)

This article shares the installation and configur...

Nodejs plug-in and usage summary

The operating environment of this tutorial: Windo...

Example of disabling browser cache configuration in Vue project

When releasing a project, you will often encounte...

How to implement a simple HTML video player

This article introduces the method of implementin...

Summary of the differences between get and post requests in Vue

The operating environment of this tutorial: Windo...

How to use shell scripts in node

background During development, we may need some s...

Share 16 burning flame effect English fonts treasure trove

We live in a visual world and are surrounded by m...

Detailed explanation of Vue lazyload picture lazy loading example

Documentation: https://github.com/hilongjw/vue-la...

React new version life cycle hook function and usage detailed explanation

Compared with the old life cycle Three hooks are ...

Use Docker to build a Git image using the clone repository

Overview I have been using Docker for more than a...

The difference between VOLUME and docker -v in Dockerfile

There are obvious differences between volume moun...

Vue+openlayer5 method to get the coordinates of the current mouse slide

Preface: How to get the coordinates of the curren...

Vue implements QR code scanning function (with style)

need: Use vue to realize QR code scanning; Plugin...

Issues with using Azure Container Registry to store images

Azure Container Registry is a managed, dedicated ...