The difference between break and last in nginx

Time:2021-3-30

Let’s start with the difference

  • Last, the rewritten rule will continue to match the following location with the rewritten value.
  • Break, the rewritten rule, will not match the following location. Using the new rules, an HTTP request is initiated directly.

Nginx configuration file

server {
        listen 88;
        server_name _;
        location /break { # location 1
          rewrite ^/break/(.*)$ /bak/$1 break;
        }
        location /last {  # location 2
          rewrite ^/last/(.*)$  /bak/$1 last;
        }

        location /bak {  # location 3
          default_type text/html;
          return 200 $uri;
        }

}

visithttp://rumenz.com:88/break/one

Hit location1, the browser address bar does not change, directly to find/nginx/html/bak/oneFile. Since there is no such file, 404 is returned.

browser

The difference between break and last in nginx

Nginx error( error.log )Log

/nginx/html/bak/one failed (2: No such file or directory)

breakIndicates that the match will stop after rewritinglocationBlock.

visithttp://rumenz.com:88/last/one

Hit location2, the browser address bar does not change, rematch tolocation3
The difference between break and last in nginx

Last means to jump to the location block after rewriting and match with the rewritten address again

breakandlastUse scenarios of

break

File download, hide and protect the real file server.

location /down {
  rewrite ^/down/(.*)$ https://rumenz.com/file/$1 break;
}

last

The interface address is rewrittenhttps://rumenz.com/api/listRewrite ashttps://rumenz.com/newapi/list

location /api {
  rewrite ^/api/(.*)$ /newapi/$1 last;
}

location /newapi {
  default_type Application/json;
  return 200 '{"code":200,"msg":"ok","data":[" JSON.IM "," JSON format "]} ';
}

Focus on WeChat official account: [entry station], unlock more knowledge points

The difference between break and last in nginx