Nginx's use of summary (four)

Nginx's use of summary (four)

rewrite configuration

The configuration rewrite nginx nginx configuration is more central part, may be implemented rewrite jump domain (redirect), URL rewriting (pseudo-static), the separation movement (jump domain, and to achieve accelerated access CDN). rewrite rely pcre library module is used ngx_http_rewrite_module.

 

rewrite the relevant directive

if instruction

Format: if (conditional)} {specific rewrite rules

  • Conditions Example:

Nginx conditional statement has built-in variables, logical judgment and a target string of three parts.
Wherein the variables are built nginx fixed, non-defined variables, such as $ request_method, $ request_uri like.
Analyzing symbol has logic =,! =, ~, ~ * ~,!,! ~ *.
! Represents a negation, ~ to match the symbol, which is right regular expression, case sensitive, and ~ * is case-insensitive matching.
Target string can be a regular expression, usually without quotes, but the expression has a special symbol, such as spaces, braces, semicolons, etc., need to be enclosed in single quotes.

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

When the process request is POST, direct return 405 status code. if supported with return instructions.

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

user_agent request with MSIE (IE browser) character 403 directly returns a status code.

If you want to while limiting multiple user_agent, it can also be written like this:

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

When requested file does not exist, it will perform the following rewrite rules.

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

\ D represent numbers, {9,12} indicates the number of the number that appears is 9 to 12 times, such as gid = 123456789 is qualified, it will perform the following rewrite rules.

 

break and last instruction

The same two instructions usage, but different meanings, we need to put the end of the rewrite rules to control whether the links rewritten continue to be configured to perform nginx (mainly rewrite, return instruction).

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;                 #打开rewrite日志,在error.log中
    rewrite /1.html /2.html;
    rewrite /2.html /3.html;
}

Reload 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

It explained that it had to jump from 1.html 3.html, actual access to a 3.html.

View Log:

# 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;
}

Reload 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

Description This time is to jump from 1.html 2.html, did not continue to the next jump.

View Log:

# 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;
}

Reload 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 Log:

# 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"

Description This time is to jump from 1.html 2.html, did not continue to the next jump. Configuration and break last action consistent server portion.

 

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;
    }
}

Reload 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 Log:

# 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 matched 1.html, 1.html jump to 2.html; then matched 2.html, 2.html and jump to 3.html; next matched 3.html, 3.html jumps to b .html; b.html match will continue, but to no match, the access b.html, because b.html absence, status code 404 is returned.

 

Example 5:
If we use the location in the server part, that the role of the last break and there is a difference.

# 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;
    }
}

Reload 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 Log:

# 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"

It can be seen only rewrite once, from 1.html 2.html directly jump to withdraw, location is no longer part of the back of the executed.

 

Example 6:

If we use the location in the server part, that the role of the last break and there is a difference.

# 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;
    }
}

Reload 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 Log:

# 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"

1.html 2.html start to jump, because Last, so the following paragraphs in this location is no longer performed, but will continue to the next location segment, the last matching 2.html (because / is more accurate than ), to jump from 2.html a.html, because a.html absence, status code 404 is returned.

In summary, we can conclude that:

* 当rewrite规则在location{}外,break和last作用一样,遇到break或last后,其后续的rewrite/return语句不再执行。但后续有location{}的话,还会近一步执行location{}里面的语句,当然前提是请求必须要匹配该location。

* 当rewrite规则在location{}里,遇到break后,本location{}与其他location{}的所有rewrite/return规则都不再执行。

* 当rewrite规则在location{}里,遇到last后,本location{}里后续rewrite/return规则不执行,但重写后的url再次从头开始执行所有规则,哪个匹配执行哪个。

 

return usage

return instruction is generally used to direct client requests the response status code is returned. All nginx configuration at the back of the return within the role are invalid. You may be used in the server, location, and if the configuration.

In addition to support with the status code, you can also link with string and url.

Return status code

Example 1:

server {
    listen 80;
    server_name www.1.com;
    return 403;
    rewrite /(.*) /abc/$1;               #该行配置不会被执行
}

.*Means all, $ 1 for the previous.*

# 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>               #返回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;               #该行配置不会被执行    
    }
    
    #如果下面还有其他配置,会被执行
    ......
}
# 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                #返回405
Server: nginx
Date: Mon, 11 Mar 2019 08:20:55 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive

 

Returns a 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, otherwise it will 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

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

  • Combat scenarios:

Background: The website was hacked, all in Baidu click to request this website, all jump to a gambling site.

By nginx solve:

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

If written: return http://$host$reauest_uri;this will prompt the browser "redirected too many times."

# 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;              #该行配置不会被执行
}

Note: you must be in the back of the return url http://or https://beginning.

# 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              #临时重定向到www.baidu.com

url front status code may be added, but only 301 or 302, if it is 200, it becomes url string.

# 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 rules

格式:rewrite regex replacement [flag]

* Rewrite configuration can take effect in the server, location, and if the configuration section

* Regex is a regular expression for matching, it will not match the $ host (domain name)

* Replacement is the goal of jump uri, can with http: // or https: // at the beginning, you can also omitted $ host, $ request_uri write directly part (ie request link)

* Flag, to set the behavior of uri rewrite process, which break, last, redirect, permanent. the difference is that redirect and permanent, temporary redirection redirect (302), while permanent permanent redirection (301).
  For user access, it is consistent both effect; but for search engine crawlers, using 301 more conducive to SEO. Therefore, the proposed replacement is http: // or https: // at the beginning of, flag the use of permanent

Example 1:

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

Note: * as a regular expression, with () enclosed in the back of the URL can call it first appears () call with a $ 1, () with $ 2 to call the second occurrence, and so on.

Example 2:

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

Description: In replacement, the support variable, here's the link $ request_uri is requested by the client.

Example 3:

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

Description: rewrite the rules in this case there is a problem, will result in a continuous loop, and nginx have a maximum limit 50 times, more than 50 times the cycle will fail.

Change setting:

# 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;
    }
}

Reload 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, it has been in circulation / abc, until the cycle 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 the break in the rewrite, the cycle can be avoided.

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: a conditional increase, the cycle can be avoided.

Change setting:

# 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;
    }
}

Reload 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 conditional, no longer circulate, if eligible, direct redirect.

 

nginx global variables

Variable Description
Parameter $ args request, such as the $ args www.123.com/1.php?a=1&b=2. 1 & B = is = A 2
$ CONTENT_LENGTH information in the HTTP request "the Content-the Length"
$ HTTP request the content_type information in the "Content-Type"
value of the parameter corresponding to the root $ content_root nginx virtual host configuration file
$ DOCUMENT_URI URI does not contain instructions in the current request, such as the www.123.com/1.php?a=1&b=2 $ document_uri is 1.php, does not contain the parameters behind the
$ host host header that domain name
Details $ http_user_agent client, that is the identity of the browser, can be specified with -A curl
the cookie information $ http_cookie client
$ limit_rate if nginx server use limit_rate configure the display network speed is displayed, it does not set the display to 0
$ REMOTE_ADDR client public network ip
Port $ remote_port client
$ remote_user if nginx have configure authentication, this variable represents the client authentication username
$ request_body_file do name of local resources sent to the back-end server, reverse proxy
mode $ request_method the requested resource, GET / PUT / DEL ETE, etc.
Path name of the resource file $ request_filename current request, the equivalent of $ document_root / $ document_uri combination of
links $ request_uri request, including $ document_uri and $ args
agreements $ scheme requests, such as the FTP, HTTP, HTTPS
$ SERVER_PROTOCOL client requests a resource version of the protocol used, such as HTTP / 1.0, HTTP / 1.1, HTTP / 2.0 , etc.
$ the server_addr server IP address
host name $ server_name server
port number $ SERVER_PORT server
$ URI and $ DOCUMENT_URI same
referer at $ HTTP_REFERER client requests , popular talk is that the request is a link through which to skip, you can specify a curl -e

 

Scene using the exemplary production nginx

Jump domain name (domain name redirection)

Example 1 (without conditions):

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

Change setting:

# 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;
}

Reload 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跳转到www.2.com

Example 2 (conditional):

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

Change setting:

# 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;
    }
}

Reload 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                #是www.1.com时照常访问

# 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/                     #是1.com时301跳转到www.2.com

Example 3 (http Jump to https):

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

Change setting:

# 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;
}

Reload 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跳转到https://www.2.com

If you own https requests do not worry, because the request is https port 443 instead of 80 ports.

Example 4 (secondary directory domain names):

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

Change setting:

# 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;
}

Reload 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跳转到http://www.2.com/aaa/

Example 5 (separation static requests):

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

or

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

Change setting:

# 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;
    }
}

Reload 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跳转到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跳转到http://img.2.com/abc/1.j

 

Hotlink Protection

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;            #或者直接 return 403;
        }
    }
    ......
}

Description:

Where * is a wildcard, and n * is not inside a meaning;

It refers to a case where none (curl -e test) Referer absence;

blocked refers to the value of the case referer header is a firewall or proxy server to delete or disguised,
        in this case, the value of the referer header is not with http: // or https: // behind with (curl -e beginning referer not with http: // or https: // at the beginning).
        
curl -e specify the source URL

Change setting:

# 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

提示404 Not Found说明没有问题

# 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

从www.3.com过来的请求直接返回403,因为http://www.3.com不是白名单中的referer

 

Pseudo-static

Example 7 (such as pseudo-static discuz):

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;
}

 

and a plurality of rewrite conditions

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;
    }
}

Change setting:

# 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;                 #任意定义一个状态码
        }
    }
}

Reload 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

We can see, this write will complain, because if nginx does not support nested in if in order to achieve a number of conditions and may do so:

Change setting:

# 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;
    }   
}

Reload 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                  #返回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                  #返回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             #返回406
Server: nginx
Date: Wed, 24 Apr 2019 14:07:22 GMT
Content-Type: text/html
Content-Length: 172
Connection: keep-alive

You can see, the definition of conditions must be fulfilled, it will return 406.

Configuration location

Grammar rules:

nginx location syntax rules: location [=|~|~*|^~] /uri/ { … }variable location matching nginx is $ uri.

symbol Explanation
= Exact matching
^~ Uri represents the beginning of a specified character or string
~ It represents the case-sensitive regular match
~* Indicate a case-insensitive regular match
/ General match, any requests are matched to the

Rule priority:

=  高于  ^~  高于  ~* 等于 ~  高于  /

Rule Examples:

location = "/12.jpg" { ... }
如:
www.1.com/12.jpg 匹配
www.1.com/abc/12.jpg 不匹配

location ^~ "/abc/" { ... }
如:
www.1.com/abc/123.html 匹配
www.1.com/a/abc/123.jpg 不匹配

location ~ "png" { ... }
如:
www.1.com/aaa/bbb/ccc/123.png 匹配
www.1.com/aaa/png/123.html 匹配

location ~* "png" { ... }
如:
www.1.com/aaa/bbb/ccc/123.PNG 匹配
www.1.com/aaa/png/123.html 匹配


location /admin/ { ... }
如:
www.1.com/admin/aaa/1.php 匹配
www.1.com/123/admin/1.php 不匹配

note:

有些资料上介绍location支持不匹配 !~,
如: location !~ 'png'{ ... }
这是错误的,location不支持 !~

如果有这样的需求,可以通过if来实现,
如: if ($uri !~ 'png') { ... }

location优先级小于if

 

Published 370 original articles · won praise 88 · views 290 000 +

Guess you like

Origin blog.csdn.net/qq_35029061/article/details/100102730