Detailed explanation of Nginx configuration block location and rewrite

Table of contents

1. Detailed explanation of location configuration block

1. location can be roughly divided into three categories

2.location common matching rules

3. The priority of location matching

4. Location matching process

5. The actual use of location

2. The nginx global variables commonly used in the if module

3. Detailed explanation of rewrite

1. Introduction to rewrite

2. Rewrite realizes the jump principle

3.rewrite execution order

4.rewrite configuration field format

6. Rewrite application example

(1) Jump based on domain name

3. Jump to the specified path of the new domain name based on the old domain name

4. Jump based on parameter matching

1. Detailed explanation of location configuration block

1. location can be roughly divided into three categories

  • Exact match: location = / { ... }

  • General matching: location / { ... }

  • Regular match: location ~ / { ... }

2.location common matching rules

= Exact match using normal characters (exact match)
~ Case sensitive matching (regex available)
~* Case-insensitive matching (regex available)
^~ Prefix matching (that is, the path is matched to the beginning and will not continue to match the deeper path)
!~ Inverse match , case sensitive
!~* Inverse match, case insensitive

3. The priority of location matching

(1) exact match = /.../...

(2) prefix matching ^~ /.../...

(3) regular match ~ or ~* /.../...

(4) General prefix matching /.../...

(5) Universal match /

4. Location matching process

If only one match is satisfied and they do not affect each other, then go directly to the matched location.

If there are multiple forms of location, match them according to the following process:

(1) If the exact match is successful, go directly to the exact match;

(2) If not, it depends on whether the screened out is a prefix match or a general match* *(path length that is more than satisfied)**;

——> If it is a general match , it depends on whether there is a regular match, if there is a regular match, the regularity is high ;

——> If the regular pattern matches multiple matches, the one with the higher priority in the configuration file will be selected .

——> If the filter is a prefix match , then ignore the regular match;

(3) Only when the exact, prefix, regular, and general are not matched will the general match be looked at.

5. The actual use of location

In actual website use, there are at least three matching rule definitions:

(1) Directly match the home page of the root directory of the website

It is more frequent to access the homepage of the website through the domain name. Using this will speed up the processing, such as the official website. It can be a static home page, or it can be directly forwarded to the back-end application server.


location = /index.html {
    root   html;
    index  index.html index.htm;
}

(2) Handle static file requests

This is the strength of nginx as an http server. There are two configuration modes, directory matching or suffix matching, choose one or use it together.

location ^~ /static/ {
    root /webroot/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}

(3) General rules

For example, it is used to forward dynamic requests with .php and .jsp suffixes to the back-end application server. Non-static file requests are dynamic requests by default.


location / {
    proxy_pass http://tomcat_server;
}

2. The nginx global variables commonly used in the if module

$args : This variable is equal to the parameters in the request line, same as $query_string $content_length : Content-length field in the request header. $content_type : The Content-Type field in the request header. $document_root : The value specified in the root directive for the current request. $host : request host header field, otherwise server name. $http_user_agent: Client agent information $http_cookie: Client cookie information $limit_rate: This variable can limit the connection rate. $request_method : The action requested by the client, usually GET or POST. $remote_addr : IP address of the client. $remote_port : The port of the client. $remote_user : The username that has been authenticated by the Auth Basic Module. $request_filename : The file path of the current request, generated by the root or alias command and the URI request. $scheme : HTTP scheme (eg http, https). $server_protocol : The protocol used by 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 on which the request arrives at the server. $request_uri : The original URI containing the request parameters, without the hostname, such as: "/foo/bar.php?arg=baz". $uri : The current URI without request parameters, $uri does not contain the hostname, such as "/foo/bar.html". $document_uri : Same as $uri.

3. Detailed explanation of rewrite

1. Introduction to rewrite

The rewrite function is to use the global variables provided by nginx or the variables set by yourself, combined with regular expressions and tag bits to realize URL rewriting and redirection . For example: after changing the domain name, it is necessary to keep the old domain name able to jump to the new domain name, a certain web page needs to jump to the new page, anti-leeching of the website, etc.

rewrite can only be placed in server{}, location{}, if{}, and by default it can only work on the string after the domain name except the passed parameters , such as http://www.abc.com/abc/ bbs/index.php?a=1&b=2 only rewrites /abc/bbs/index.php.

2. Rewrite realizes the jump principle

Need to support module: ngx_http_rewrite_module

  • Nginx : supports URL rewriting and if condition judgment through modules, but does not support else (single branch) ;

  • Jump : jump from one location to another location, the jump can be executed up to 10 times, after which nginx will return 500 error;

  • PCRE support : perl compatible regular expression syntax rule matching;

  • Override the module set command : create a new variable and set its value.

3.rewrite execution order

First (if present) the rewrite directive inside the server block is executed. ——>Execute location matching. ——> (if exists) execute the rewrite command in the selected location.

4.rewrite configuration field format

rewrite <regex> <replacement> [flag];

  • regex: Indicates regular matching rules;

  • replacement: Indicates the content after the jump;

  • flag : Indicates the flag tag supported by rewrite.

Commonly used flag flags

last After the matching of this rule is completed, the rewritten url matching will not be terminated , and it is generally used in server and if.
break This rule is terminated when the matching is completed, and the rewritten url matching is terminated , which is generally used in location.
redirect Return 302 temporary redirection , and the browser address bar will display the redirected URL address.
permanent Return 301 permanent redirection , and the browser address bar will display the redirected URL address.

6. Rewrite application example

(1) Jump based on domain name

For business transfer, the old domain name www.abc.com needs to be transferred to the new domain name www.def.com .

vim /usr/local/nginx/conf/nginx.conf
...
server {
    ...
    location / {
        #添加域名重定向
        #$host为rewrite全局变量,代表请求主机头字段或主机名。
        if ($host = 'www.abc.com'){    
            #重写域名必须以协议开头(http或https),$1为前面正则表达式匹配的内容。
            rewrite ^/(.*)$ http://www.def.com/$1 permanent;
        }
        root   html;
        index  index.html index.htm;
    }
}

img

(2) Jump based on client IP access

The new version is online, requiring all IPs to access any content to display a fixed maintenance page, and only our company's IP access is normal.

vim /usr/local/nginx/conf/nginx.conf
...
server {
    ...
    #自定义变量用于判断是否是合法的IP标记
    set $rewrite true;                          #设置变量$rewrite,变量值为boole值true
    #判断是否为合法IP
    if ($remote_addr = "192.168.116.20"){       #当客户端IP为192.168.80.10时,将变量值设为false,不进行重写
        set $rewrite false;
    }
    #除了合法IP,其它都是非法IP,进行重写跳转维护页面
    if ($rewrite = true){                       #当变量值为true时,进行重写
        rewrite (.+) /weihu/index.html;         #将域名后边的路径重写成/weihu.html后转发(因为这里不重写域名所有可以不用从协议开头)
    }
    location = /weihu/index.html {
        root /var/www/html;                     #网页返回/var/www/html/weihu/index.html的内容
    }
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

img

Create a maintenance page

img

Use a non-specified ip to access the test

img

3. Jump to the specified path of the new domain name based on the old domain name

The /bbs business change under a certain site needs to be stored in the /old/bbs directory of the new domain name.

vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  bbs.abc.com www.abc.com;       #域名修改   
    charset utf-8;
    access_log  /var/log/nginx/www.abc.com-access.log;
    
    #添加
    location /bbs {
        rewrite (.+) http://www.abc.com/old$1 permanent;    #这里的$1为位置变量,代表/bbs
    }
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

img

Add domain name resolution to ensure access

img

Move the business under the old directory /bbs to the new site under /old/bbs

img

Visit /bbs (bbs.abc.com/bbs) under the old domain name

img

4. Jump based on parameter matching

Use if {...} to judge variables, realize access to page1, page2, and page3 in the root directory, and jump to the home page.

add configuration

vim /usr/local/nginx/conf/nginx.conf
server {
        #添加
        #$request_uri代表包含请求参数的原始URI,不包含主机名
        if ($request_uri ~* ^/page(1|2|3)\.html) {
            rewrite (.+) http://www.abc.com;
        }
}

img

Test access ( www.abc.com/page1.html )

img

Guess you like

Origin blog.csdn.net/wlc1213812138/article/details/131421021