Nginx – Regex nginx location with named location

nginxregex

I have the following set up – a production version of some software;

location @myradio {
    rewrite ^/myradio/([^/]+)/([^/]+)/?  /myradio/index.php?module=$1&action=$2 last;
    rewrite ^/myradio/([^/]+)/?          /myradio/index.php?module=$1 last;
}

location /myradio {
    alias /usr/local/www/myradio/src/Public;
    try_files $uri $uri/ @myradio;

    location ~ \.php {
        fastcgi_index   index.php;
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $request_filename;
        fastcgi_pass    php5-fpm;
    }
}

and several development versions – there's also myradio-lordaro, among others.

location @myradiodev {
    rewrite ^/myradio-([^/]+)/([^/]+)/([^/]+)/?  /myradio-$1/index.php?module=$2&action=$3 last;
    rewrite ^/myradio-([^/]+)/([^/]+)/?          /myradio-$1/index.php?module=$2 last;
}

location /myradio-dev {
    alias /usr/local/www/myradio-dev/src/Public;
    try_files $uri $uri/ @myradiodev;

    location ~ \.php {
        fastcgi_index   index.php;
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $request_filename;
        fastcgi_pass    php5-fpm;
    }
}

Both of these work perfectly fine, but copying out the same /myradio-* config several times seems inefficient and I feel like I can do better.

Is it possible to generalise the development configs into one that uses regex to redirect nginx to the correct location? The @myradiodev is used successfully for all dev versions, so I don't believe that's the issue, but my own attempts to do it have just resulted in various 403 or 404 errors, with no clear idea where nginx is trying to access.

[Other recommendations as to how to clean this up appreciated (was originally converted from an apache config)]

Best Answer

You can use a regular expression in the location block. (you already did that in the nested location block for php). It's announced by the tilde "~".

location ~ ^/myradio-([^/]+)

You could then use the match variable like:

alias /usr/local/www/myradio-$1/src/Public;

Or cleaner without match variable:

alias /usr/local/$request_uri/src/Public

Did not try it, but it should work.