Search code examples
regexnginxpcremunin

PCRE ^~ symbol in nginx


I have this nginx location block ( from https://munin.readthedocs.io/en/2.0.8/example/webserver/nginx.html )

location ^~ /munin-cgi/munin-cgi-graph/ {
    fastcgi_split_path_info ^(/munin-cgi/munin-cgi-graph)(.*);
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_pass unix:/var/run/munin/fastcgi-graph.sock;
    include fastcgi_params;
}

It seems like nginx is using PCRE. ^ means "assert start of string (or line, in multiline mode)" from http://www.pcre.org/original/doc/html/pcrepattern.html but I can't find what ~ means.

Thanks


Solution

  • Don't read the docs only at readthedocs.io. For comprehensive explanations, read the actual docs.

    http://nginx.org/en/docs/http/ngx_http_core_module.html#location

    I quote:

    Syntax:   location [ = | ~ | ~* | ^~ ] uri { ... }
    location @name { ... }
    Default:  —
    Context:  server, location
    

    So this tells us that ^~ is one of the operators supported by location.

    In other words: That's not part of any regular expression at all, it's a modifier.

    The documentation goes on:

    To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked [...]

    Which means that nginx tries to find a match by comparing URL prefixes first (which is fast), and if that fails, goes on to try regular expressions (which is much slower).

    A few sentences later:

    If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.

    So this means if there is a candidate match for a given URL then you can utilize ^~ to prevent nginx from trying regular expressions to find an even better match. This is a performance optimization.

    So, in plain English

    location ^~ /munin-cgi/munin-cgi-graph/ {
    }
    

    means "all locations starting /munin-cgi/munin-cgi-graph/, and don't bother looking for better matches".