Regular expressions are relatively inefficient and generally discouraged in Nginx configurations when other methods would suffice. There are a few cases here that don't require regexes:
location /clip-art/ {
# ...
}
location /Clip-Art/ {
# ...
}
location /images/ {
# ...
}
location /cgi-bin/ {
# ...
}
If you're just serving static images from at least three of those, we can make it even simpler. The ^~
prefix means that these rules will take precedence over regex-based rules, which would otherwise take precedence. While this has many uses, it can act as a security feature when dealing with directories containing only static resources. If someone manages to upload a PHP file or some other executable code that would normally be handled by a regex location, the pre-regex location (with ^~
) will win, and the file won't be executed. I've also omitted the typical $uri/
because it's not really applicable to static resource directories.
location ^~ /clip-art/ { try_files $uri =404; }
location ^~ /Clip-Art/ { try_files $uri =404; }
location ^~ /images/ { try_files $uri =404; }
location /cgi-bin/ {
# ...
}
As for the remaining conditions, Nginx is designed to match starting from the beginning of each URI. Ideally, you can handle these sorts of scenarios in your application, rather than within Nginx. However, in this specific instance, a relatively efficient regex can be written:
rewrite "^((?:/(?!designer|invitation)[^/]+){4})/?$" /clip-art$1 permanent;