Search code examples
httpnginxddos

Nginx location search-terminating match with regexp


I'm trying to set a different limit_req zone for static content.

location ^~ /img {
  limit_req zone=static burst=60 nodelay;
}
location ^~ /logos {
  limit_req zone=static burst=60 nodelay;
}
location ^~ /js {
  limit_req zone=static burst=60 nodelay;
}
location ^~ /plugin {
  limit_req zone=static burst=60 nodelay;
}

location / {
  limit_req zone=protected burst=5 nodelay;
}

This is working fine, but I want to compress those locations into one regular expression:

location ^~ /(img|logos|js|plugin) {
  limit_req zone=static burst=60 nodelay;
}

Tried this, but it is not working. Only works with ~ without ^, which will then match the location /, setting the zone back to protected. Is ^~ only working with literals? Any other way to achieve this in a clean way?


Solution

  • according to nginx documentation

    The following location is defined before the one with the proxy_pass and it matches the request of js and css files under static. This location block is used for different extensions you want to allow in your site.

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        limit_req zone=static burst=60 nodelay;
        log_not_found off;
      }
    

    Or, you can use this I think this should work fine

    location ~ ^/(img|logos|js|plugin)/ {
      root /project_root_path;
      limit_req zone=static burst=60 nodelay;
    }