Summary of Nginx usage

Keywords: Nginx curl vim PHP

Summary of the Use of Nginx (IV)

rewrite configuration

The rewrite configuration of nginx is the core part of nginx configuration. rewrite can implement domain name jump (redirection), URL rewrite (pseudo-static), dynamic and static separation (jump domain name, and connect CDN for acceleration).Rewrite relies on the pcre library, and the module used is ngx_http_rewrite_module.

 

rewrite-related instructions

if directive

Format: if (conditional judgment) {specific rewrite rule}

  • Examples of conditions:

Conditional judgment statements consist of nginx built-in variables, logical judgment symbols, and target strings.
The built-in variable is a fixed, non-custom variable for nginx, such as $request_method, $request_uri, and so on.
Logical judgment symbols are =,!=, ~, ~*,!~,!~*.
!Reverse, ~is a matching symbol, and to the right is a regular expression, case-sensitive, and ~* is case-insensitive.
The target string can be a regular expression, usually without quotation marks, but when there are special symbols in the expression, such as spaces, curly braces, semicolons, and so on, they need to be enclosed in single quotation marks.

  • Example 1:
if ($request_method = POST)
{
    return 405;
}

When the requested method is POST, a 405 status code is returned directly.The return directive is supported in if.

  • Example 2:
if ($http_user_agent ~ MSIE )
{
    return 403;
}

A request with MSIE (IE browser) characters from user_agent returns a 403 status code directly.

If you want to limit multiple user_agent s at once, you can also write as follows:

if ($http_user_agent ~ "MSIE|firefox|spider")
{
    return 403;
}
  • Example 3:
if (!-f $request_filename)
{
    rewrite Sentence;
}

When the requested file does not exist, the following rewrite rule will be executed.

  • Example 4:
if ($request_uri ~* 'gid=\d{9,12}/')
{
    rewrite Sentence;
}

d denotes a number, {9,12} denotes a number that occurs 9 to 12 times. If gid=123456789 is qualified, the following rewrite rule will be executed.

 

break and last directives

The two instructions have the same usage but different meanings and need to be placed at the end of the rewrite rule to control whether the rewritten link will continue to be executed by the nginx configuration (mainly the rewrite, return instructions).

Example 1:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;                 #Open the rewrite log in error.log
    rewrite /1.html /2.html;
    rewrite /2.html /3.html;
}

Overload Configuration:

# echo "111111" > /data/wwwroot/www.1.com/2.html

# echo "222222" > /data/wwwroot/www.1.com/2.html

# echo "333333" > /data/wwwroot/www.1.com/3.html

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html
333333

Description has jumped from 1.html to 3.html, actually accessing 3.html.

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 17:51:27 [notice] 28386#0: *1 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 17:51:27 [notice] 28386#0: *1 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 17:51:27 [notice] 28386#0: *1 "/2.html" matches "/2.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 17:51:27 [notice] 28386#0: *1 rewritten data: "/3.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

 

Example 2:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html
222222

This time, you jumped from 1.html to 2.html without continuing down.

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 18:02:18 [notice] 28507#0: *2 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:02:18 [notice] 28507#0: *2 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

 

Example 3:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    rewrite /1.html /2.html last;
    rewrite /2.html /3.html;
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html
222222

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 18:08:21 [notice] 28533#0: *3 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:08:21 [notice] 28533#0: *3 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

This time it was also jumping from 1.html to 2.html and did not proceed to the next jump.Configuring break and last in the server section works the same way.

 

Example 4:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    location / {
    rewrite /1.html /2.html;
    rewrite /2.html /3.html;
    }

    location /2.html {
    rewrite /2.html /a.html;
    }

    location /3.html {
    rewrite /3.html /b.html;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 18:18:11 [notice] 6932#0: signal 17 (SIGCHLD) received from 28533
2019/03/11 18:18:27 [notice] 28558#0: *4 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 "/2.html" matches "/2.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 rewritten data: "/3.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 "/3.html" matches "/3.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 rewritten data: "/b.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 "/1.html" does not match "/b.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [notice] 28558#0: *4 "/2.html" does not match "/b.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:18:27 [error] 28558#0: *4 open() "/data/wwwroot/www.1.com/b.html" failed (2: No such file or directory), client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

First match to 1.html, 1.html jump to 2.html; then match to 2.html, 2.html jump to 3.html; next match to 3.html, 3.html jump to b.html; b.html will continue to match, but no match, so access b.html, because b.html does not exist, so return the 404 status code.

 

Example 5:
If we use location in the server section, break and last have different roles.

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    location / {
    rewrite /1.html /2.html break;
    rewrite /2.html /3.html;
    }

    location /2.html {
    rewrite /2.html /a.html;
    }

    location /3.html {
    rewrite /3.html /b.html;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html
222222

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 18:32:55 [notice] 6750#0: *5 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:32:55 [notice] 6750#0: *5 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

You can see that rewrite only once, jumping from 1.html to 2.html, exits directly, and the subsequent location section is no longer executed.

 

Example 6:

If we use location in the server section, break and last have different roles.

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    location / {
    rewrite /1.html /2.html last;
    rewrite /2.html /3.html;
    }

    location /2.html {
    rewrite /2.html /a.html;
    }

    location /3.html {
    rewrite /3.html /b.html;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.html

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

View logs:

# tail /usr/local/nginx/logs/error.log

2019/03/11 18:38:57 [notice] 6759#0: *6 "/1.html" matches "/1.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [notice] 6759#0: *6 rewritten data: "/2.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [notice] 6759#0: *6 "/2.html" matches "/2.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [notice] 6759#0: *6 rewritten data: "/a.html", args: "", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [notice] 6759#0: *6 "/1.html" does not match "/a.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [notice] 6759#0: *6 "/2.html" does not match "/a.html", client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"
2019/03/11 18:38:57 [error] 6759#0: *6 open() "/data/wwwroot/www.1.com/a.html" failed (2: No such file or directory), client: 127.0.0.1, server: www.1.com, request: "GET HTTP://www.1.com/1.html HTTP/1.1", host: "www.1.com"

Jump from 1.html to 2.html first, because last causes the following within this location segment to no longer execute, but continues to execute the following location segment, and finally matches to 2.html (because more accurate), jumping from 2.html to a.html, and returning 404 status codes because a.html does not exist.

To sum up, we can conclude that:

*When the rewrite rule is outside of location {}, break acts like last, and subsequent rewrite/return statements are no longer executed when a break or last is encountered.However, if location {} is followed, the statement inside location {} will be executed further, provided the request must match the location.

*When the rewrite rule in location {} encounters a break, all rewrite/return rules for this location {} and other locations {} are no longer enforced.

*When the rewrite rule in location {} encounters last, subsequent rewrite/return rules in this location {} do not execute, but the rewritten url executes all rules from scratch again, which match executes which one.

 

return usage

The return directive is typically used to return a response status code directly to the requesting client.All nginx configurations after return in this scope are invalid.You can use it in server, location, and if configurations.

In addition to supporting status codes, you can also link to strings and url s.

Return status code

Example 1:

server {
    listen 80;
    server_name www.1.com;
    return 403;
    rewrite /(.*) /abc/$1;               #The row configuration will not be executed
}

. * for all, $1 for preceding. *

# vim /usr/local/nginx/conf/vhost/default.conf

server {
    listen 80 default_server;
    return 403;
    rewrite /(.*) /abc/$1;
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 e2rwejqw.com

<html>
<head><title>403 Forbidden</title></head>               #Return 403
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

 

Example 2:

server {
......
    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return 405;
        rewrite /(.*) /aaa.txt;               #The row configuration will not be executed    
    }
    
    #If there are other configurations below, they will be executed
    ......
}
# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return 405;
        rewrite /(.*) /aaa.txt;                                   
    }
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd -I

HTTP/1.1 405 Not Allowed                #Return 405
Server: nginx
Date: Mon, 11 Mar 2019 08:20:55 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive

 

Return string

Example 3:

server {
    listen 80;
    server_name www.1.com;
    return 200 "hello";
}

If you want to return a string, you must add a status code or you will get an error.

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return 200 "error";
        rewrite /(.*) /aaa.txt;                                   
    }
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd -I

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 11 Mar 2019 08:26:58 GMT
Content-Type: application/octet-stream
Content-Length: 5
Connection: keep-alive

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd
error

You can also support JSON data; write a variable; and support html code.

  • Scene Actual:

Background: The website has been hacked. All requests from Baidu to click on this website jump to a gambling website.

Solve via nginx:

server {
......
    if ( $http_referer ~ 'baidu.com' ) {
        return 200 "<html><script>window.location.href='//$host$request_uri';</script></html>";
    }
}

If it says: return http://$host$reauest_uri; this will prompt in the browser that "too many redirections have occurred".

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return 200 "<html><script>window.location.href='//$host$request_uri';</script></html>";
        rewrite /(.*) /aaa.txt;
    }
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd -I

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 11 Mar 2019 08:54:17 GMT
Content-Type: application/octet-stream
Content-Length: 79
Connection: keep-alive

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd

<html><script>window.location.href='//www.1.com/123/.htpasswd';</script></html> 

 

Return url

Example 4:

server {
    listen 80;
    server_name www.1.com;
    return http://www.baidu.com;
    rewrite /(.*) /abc/$1;              #The row configuration will not be executed
}

Note: The url following return must start with http://or https://

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return http://www.baidu.com;
        rewrite /(.*) /abc/$1;
    }
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd -I

HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Mon, 11 Mar 2019 08:44:07 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://Www.baidu.com #Temporarily redirected to www.baidu.com

The url can also be preceded by a status code, but only 301 or 302. If 200, the url becomes a string return.

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    if ( $request_uri ~ "\.htpasswd|\.bak" ) {
        return 200 http://www.baidu.com;
        rewrite /(.*) /abc/$1;
    }
}

# /usr/local/nginx/sbin/nginx -s reload

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd -I

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 11 Mar 2019 09:02:15 GMT
Content-Type: application/octet-stream
Content-Length: 20
Connection: keep-alive

# curl -x127.0.0.1:80 www.1.com/123/.htpasswd
http://www.baidu.com

 

rewrite rule

Format: rewrite regex replacement [flag]

* The rewrite configuration can take effect in the server, location, and if configuration sections

* regex is a regular expression for matching and will not match $host

* Replcement is the URI of the target jump, either starting with http://or https://or omitting $host to write the $request_uri section directly (that is, request link)

* flag, which sets rewrite's handling of uri, including break, last, redirect, permanent.The difference between redirect and permanent is that redirect is a temporary redirect (302) and permanent is a permanent redirect (301).
The results are the same for user access, but 301 is better for search engine crawlers.Therefore, it is recommended that replacement s start with http://or https://and flag uses permanent

Example 1:

location / {
    rewrite /(.*) http://www.123.com/$1 permanent;
}

Description:. * is a regular expression, enclosed in (), which can be called in subsequent URL s, first () called with $1, second () called with $2, and so on.

Example 2:

location / {
    rewrite /.* http://www.123.com$request_uri permanent;
}

Description: In replacement, variables are supported, where $request_uri is the link to the client request.

Example 3:

server {
    listen 80;
    service_name www.123.com;
    root /tmp/123.com;
    index index.html;
    rewrite /(.*) /abc/$1 redirect;
}

Note: There is a problem with the rewrite rule in this example, which causes a continuous loop, whereas nginx has a maximum limit of 50 times and loops fail more than 50 times.

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.2.com.conf 

server {
    listen 80;
    server_name www.2.com;
    index index.html;
    root /data/wwwroot/www.2.com;

    location / {
        rewrite /(.*) /abc/$1 redirect;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.2.com/1.html

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

# curl -x127.0.0.1:80 www.2.com/1.html -L
curl: (47) Maximum (50) redirects followed
# curl -x127.0.0.1:80 www.2.com/1.html -I

HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Mon, 22 Apr 2019 13:41:15 GMT
Content-Type: text/html
Content-Length: 154
Location: http://www.2.com/abc/1.html
Connection: keep-alive

# curl -x127.0.0.1:80 www.2.com/abc/1.html -I

HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Mon, 22 Apr 2019 13:41:27 GMT
Content-Type: text/html
Content-Length: 154
Location: http://www.2.com/abc/abc/1.html
Connection: keep-alive

You can see that the cycle / abc is going on until the cycle is more than 50 times.

Example 4:

server {
    listen 80;
    service_name www.123.com;
    root /tmp/123.com;
    index index.html;
    rewrite /(.*) /abc/$1 break;
}

Note: Use break in rewrite to avoid loops.

Example 5:

server {
    listen 80;
    service_name www.123.com;
    root /tmp/123.com;
    index index.html;
    if ($request_uri !~ '^/abc/')
    {
        rewrite /(.*) /abc/$1 redirect;
    }
}

Description: Adding a conditional judgment can also avoid looping.

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.2.com.conf 

server {
    listen 80;
    server_name www.2.com;
    index index.html;
    root /data/wwwroot/www.2.com;

    if ($request_uri !~ '^/abc/')
    {
        rewrite /(.*) /abc/$1 redirect;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.2.com/1.html -I

HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Mon, 22 Apr 2019 13:48:42 GMT
Content-Type: text/html
Content-Length: 154
Location: http://www.2.com/abc/1.html
Connection: keep-alive

# curl -x127.0.0.1:80 www.2.com/abc/1.html -I

HTTP/1.1 404 Not Found
Server: nginx
Date: Mon, 22 Apr 2019 13:50:21 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive

Once you have a conditional judgment, you do not loop anymore, and if you are satisfied, redirect directly.

 

nginx global variable

Variable Description
$args. Parameters in the request, such as www.123.com/1.php?A=1&b=2, $args is a=1&b=2
$content_length "Content-Length" in http request information
$content_type "Content-Type" in http request information
$content_root The value corresponding to the root parameter in the nginx virtual host configuration file
$document_uri) The URI for the directive that is not included in the current request, such as www.123.com/1.php?A=1&b=2, $document_uri is 1.php and does not contain the following parameters
$host * Host header, domain name
$http_user_agent Client details, also known as the browser's identity, can be specified with curl-A
$http_cookie * cookie information for the client
$limit_rate] If the nginx server uses limit_rate to configure the display network rate, it will be displayed and 0 if it is not set
$remote_addr* client public network ip
$remote_port * port of client
$remote_user] If nginx has configuration authentication, this variable represents the client-authenticated user name
$request_body_file The name of the local resource sent to the back-end server when acting as a reverse proxy
$request_method How resources are requested, GET/PUT/DELETE, etc.
$request_filename The path name of the resource file currently requested is equivalent to a combination of $document_root/$document_uri
$request_uri Links requested, including $document_uri and $args
$scheme] Requested protocols, such as ftp,http,https
$server_protocol Client requests the version of the protocol used by the resource, such as HTTP/1.0, HTTP/1.1, HTTP/2.0, etc.
$server_addr* Server IP Address
$server_name The host name of the server
$server_port The port number of the server
$uri] is the same as $document_uri
$http_referer RefererWhen a client requests a request, it is common to say which link the request was jumped through, which can be specified by curl-e

 

Example scenarios used in nginx production environments

Domain Name Jump (Domain Name Redirection)

Example 1 (unconditional):

server {
    listen 80;
    server_name www.1.com;
    rewrite /(.*) http://www.2.com/$1 permanent;
    ......
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf 

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    rewrite /(.*) http://www.2.com/$1 permanent;
}

Overload Configuration:

 /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com -I

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Apr 2019 12:47:15 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://Www.2.com/ 301 Jump to www.2.com

Example 2 (with conditions):

server {
    listen 80;
    server_name www.1.com 1.com;
    if ($host != 'www.1.com') {
        rewrite /(.*) http://www.2.com/$1 permanent;
    ......
    }
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf 

server {
    listen 80;
    server_name www.1.com 1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    if ($host != 'www.1.com') {
    rewrite /(.*) http://www.2.com/$1 permanent;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com -I

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 24 Apr 2019 12:52:24 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Sat, 06 Apr 2019 09:42:39 GMT
Connection: keep-alive
ETag: "5ca8748f-a"
Accept-Ranges: bytes                #Visit www.1.com as usual

# curl -x127.0.0.1:80 1.com -I

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Apr 2019 12:52:33 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://Www.2.com/ #301 jumps to www.2.com when 1.com

Example 3 (http jumps to https):

server {
    listen 80;
    server_name www.1.com;
    rewrite /(.*) https://www.2.com/$1 permanent;
    ......
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf 

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    rewrite /(.*) https://www.2.com/$1 permanent;
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com -I

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Apr 2019 12:59:28 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: https://Www.2.com/ 301 Jump to https://www.2.com

Don't worry if it's the requested https itself, because https requests port 443 instead of port 80.

Example 4 (Domain name access secondary directory):

server {
    listen 80;
    server_name www.1.com;
    rewrite /(.*) https://www.2.com/aaa/$1 last;
    ......
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf 

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    rewrite /(.*) http://www.2.com/aaa/$1 last;
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com -I

HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Wed, 24 Apr 2019 13:05:18 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Location: http://Www.2.com/aaa/ #302 Jump to http://www.2.com/aaa/

Example 5 (static request separation):

server {
    listen 80;
    server_name www.1.com;
    location ~* ^.+.(jpg|jpeg|gif|css|png|js)$
    {
        rewrite /(.*) https://www.2.com/$1 permanent;
    }
    ......
}

perhaps

server {
    listen 80;
    server_name www.1.com;
    if ( $uri ~* (jpg|jpeg|gif|css|png|js)$)
    {
        rewrite /(.*) https://www.2.com/$1 permanent;
    }
    ......
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf 

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    location ~* ^.+.(jpg|jpeg|gif|css|png|js)$
    {
        rewrite /(.*) http://img.2.com/$1 permanent;
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 www.1.com/1.jpg -I

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Apr 2019 13:22:30 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://Img.2.com/1.jpg #301 Jump to http://img.2.com/1.jpg

# curl -x127.0.0.1:80 www.1.com/abc/1.jpg -I

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Apr 2019 13:21:42 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://Img.2.com/abc/1.jpg #301 Jump to http://img.2.com/abc/1.j

 

Anti-theft chain

Example 6:

server {
    listen 80;
    server_name www.1.com;
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|rar|zip|flv)$
    {
        valid_referers none blocked server_names *.1.com 1.com *.2.com 2.com;
        if ($invalid_referer)
        {
            rewrite /(.*) http://img.1.com/images/forbidden.png; #or direct return 403;
        }
    }
    ......
}

Explain:

*This is a wildcard, not a regular *

none refers to the case where referer does not exist (curl-e test);

blocked refers to the case where the value of the referer header is deleted or disguised by a firewall or proxy server.
In this case, the referer header value does not start with http://or https://
        
Curl-e Specify Source Web Address

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    location ~* ^.+.(jpg|jpeg|gif|css|png|js|rar|zip|flv)$
    {
        valid_referers none blocked server_names *.1.com 1.com *.2.com 2.com;
        if ($invalid_referer)
        {
            return 403;
        }
    }
}
# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -e "http://www.2.com/1.html" -x127.0.0.1:80 www.1.com/abc/1.jpg -I

HTTP/1.1 404 Not Found
Server: nginx
Date: Wed, 24 Apr 2019 13:50:42 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive

//Hint 404 Not Found explanation OK

# curl -e "http://www.3.com/1.html" -x127.0.0.1:80 www.1.com/abc/1.jpg -I

HTTP/1.1 403 Forbidden
Server: nginx
Date: Wed, 24 Apr 2019 13:50:47 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive

//Requests from www.3.com returned 403 directly because http://www.3.com is not a referer on the whitelist

 

Pseudo-static

Example 7 (such as discuz pseudostatic):

location /  {
    rewrite ^([^\.]*)/topic-(.+)\.html$ $1/portal.php?mod=topic&topic=$2 last;
    rewrite ^([^\.]*)/forum-(\w+)-([0-9]+)\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
    rewrite ^([^\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
    rewrite ^([^\.]*)/group-([0-9]+)-([0-9]+)\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
    rewrite ^([^\.]*)/space-(username|uid)-(.+)\.html$ $1/home.php?mod=space&$2=$3 last;
    rewrite ^([^\.]*)/(fid|tid)-([0-9]+)\.html$ $1/index.php?action=$2&value=$3 last;
}

 

rewrite multiple conditions and

Example 8:

location / {
    set $rule 0;
    if ($document_uri !~ '^/abc')
    {
        set $rule "${rule}1";
    }
    if ($http_user_agent ~* 'ie6|firefox')
    {
       set $rule "${rule}2";
    }
    if ($rule = "012")
    {
        rewrite /(.*) /abc/$1 redirect;
    }
}

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;
    if ($request_uri ~ "^/abc/")
    {
        if ($http_user_agent ~ 'IE|chrome')
        {
            return 406;                 #Any definition of a status code
        }
    }
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

nginx: [emerg] "if" directive is not allowed here in /usr/local/nginx/conf/vhost/www.1.com.conf:11
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

You can see that writing this way will result in errors, because nginx does not support nesting if in if. To achieve more than one condition, you can do this:

Modify the configuration:

# vim /usr/local/nginx/conf/vhost/www.1.com.conf

server {
    listen 80;
    server_name www.1.com;
    index index.html;
    root /data/wwwroot/www.1.com;

    rewrite_log on;

    set $rule 0;
    if ($request_uri ~ "^/abc/")
    {
        set $rule "${rule}1";
    }
    if ($http_user_agent ~ 'IE|chrome')
    {
        set $rule "${rule}2";
    }
    if ($rule = "012")
    {
        return 406;
    }   
}

Overload Configuration:

# /usr/local/nginx/sbin/nginx -t

# /usr/local/nginx/sbin/nginx -s reload

Access Test:

# curl -x127.0.0.1:80 -A "kdjshd" www.1.com/abc/1.html -I

HTTP/1.1 404 Not Found                  #Return 404
Server: nginx
Date: Wed, 24 Apr 2019 14:00:47 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
# curl -x127.0.0.1:80 -A "kdjshdchrome" www.1.com/abcd/1.html -I

HTTP/1.1 404 Not Found                  #Return 404
Server: nginx
Date: Wed, 24 Apr 2019 14:04:31 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
# curl -x127.0.0.1:80 -A "kdjshdchrome" www.1.com/abc/1.html -I

HTTP/1.1 406 Not Acceptable             #Return 406
Server: nginx
Date: Wed, 24 Apr 2019 14:07:22 GMT
Content-Type: text/html
Content-Length: 172
Connection: keep-alive

As you can see, 406 will only be returned if the defined conditions are met at the same time.

location configuration

Rule of grammar:

nginx location syntax rule: location [=|~|~*|^~]/uri/ {...}, the location of nginx matches a variable of $uri.

Symbol Explain
= Represents an exact match
^~ Indicates uri begins with a specified character or string
~ Represents a case-sensitive regular match
~* Represents a case-insensitive regular match
/ Universal match, any request will match to

Rule priority:

=above ^~above ~* equals ~above/

Example rule:

location = "/12.jpg" { ... }
//For example:
www.1.com/12.jpg matching
www.1.com/abc/12.jpg Mismatch

location ^~ "/abc/" { ... }
//For example:
www.1.com/abc/123.html matching
www.1.com/a/abc/123.jpg Mismatch

location ~ "png" { ... }
//For example:
www.1.com/aaa/bbb/ccc/123.png matching
www.1.com/aaa/png/123.html matching

location ~* "png" { ... }
//For example:
www.1.com/aaa/bbb/ccc/123.PNG matching
www.1.com/aaa/png/123.html matching


location /admin/ { ... }
//For example:
www.1.com/admin/aaa/1.php matching
www.1.com/123/admin/1.php Mismatch

Be careful:

There are some references to location support mismatches!~,
Example: location! ~'png'{...}
This is a mistake, location is not supported!~

If there is such a requirement, it can be achieved through if,
For example: if ($uri!~'png') {...}

location priority is less than if

 

Posted by rubric on Tue, 27 Aug 2019 18:10:45 -0700