Using nginx and CodeIgniter, I have a location block in my server config that handles the routing for my project like this:
location /beta/ {
try_files $uri $uri/ /beta/index.php;
}
This works fine, but I perform backups on this CodeIgniter project and move them to another folder. The "beta" project gets renamed (with a time-stamp). So I have a backups folder with CodeIgniter projects named as such:
backups/beta_2013_05_21_0857
backups/beta_2012_05_23_0750
What I'm trying to do is create another location rule that handles these variable-named projects, but all attempts at using regex so far have failed. If I name the project directly it does work.
location /backups/beta_2013_05_21_0857 {
try_files $uri $uri/ /backups/beta_2013_05_21_0857/index.php;
}
But obviously I don't want to create a rule for each and every folder. Does anyone have any idea on how to solve this? This is the how I was trying to solve the problem:
location /backups/^\w+$/ {
try_files $uri $uri/ /backups/$1/index.php;
}
Support for regular expressions is one of the powerful features of NGINX, but regexes can be complex and difficult to get right, especially if you don't work with them regularly. NGINX allows regexes in multiple parts of a configuration, for example locations, maps, rewrites, and server names.
To find a location match for an URI, NGINX first scans the locations that is defined using the prefix strings (without regular expression). Thereafter, the location with regular expressions are checked in order of their declaration in the configuration file.
Nginx uses the PCRE library.
Every NGINX configuration file will be found in the /etc/nginx/ directory, with the main configuration file located in /etc/nginx/nginx. conf .
Two possible problems:
You don't have any brackets in your regex so it's not going to be a capturing group. And you missed out the ~* command to tell Nginx to do a regex match.
location ~* ^/backups/(\w+)$ {
try_files $uri $uri/ /backups/$1/index.php;
}
The last parameter in a try_files is magic. It doesn't actually try to see if the file exists. Instead it rewrites the request URI with the last parameter and reprocesses the request, which is moderately surprising. To fix this you can (and should) fall back to either a 404 or other page.
location ~* ^/backups/(\w+)$ {
try_files $uri $uri/ /backups/$1/index.php /404_static.html;
}
location = /404_static.html {
root /documents/projects/intahwebz/intahwebz/data/html/;
internal;
}
btw if you have further issues you should enable rewrite_log on;
which will write the matching to the servers error file at notice level, and helps figure out location matching issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With