5

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;
}

1 Answer 1

8

Two possible problems:

  1. 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;
    }
    
  2. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That did fix the problem. I need to brush up on my regular expressions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.