Using regex in nginx location block for variables

Using nginx and CodeIgniter, I have a location block in my server configuration that handles the routing for my project as follows:

location /beta/ { try_files $uri $uri/ /beta/index.php; } 

This works fine, but I back up in this CodeIgniter project and move them to another folder. The beta project is being renamed (with a timestamp). Therefore, I have a backup 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 processes these projects with variable names, but all attempts to use the regular expression have not yet worked. If I call the project directly, it works.

 location /backups/beta_2013_05_21_0857 { try_files $uri $uri/ /backups/beta_2013_05_21_0857/index.php; } 

But obviously, I do not want to create a rule for each folder. Does anyone know how to solve this? This is how I tried to solve the problem:

 location /backups/^\w+$/ { try_files $uri $uri/ /backups/$1/index.php; } 
+4
source share
1 answer

Two possible problems:

  • You do not have parentheses in your regex, so it will not be a capture group. And you skipped the ~ * command to tell Nginx to execute the regex.

     location ~* ^/backups/(\w+)$ { try_files $uri $uri/ /backups/$1/index.php; } 
  • The last parameter in try_files is magic. In fact, he is not trying to see if the file exists. Instead, it overwrites the request URI with the last parameter and processes the request, which is moderately awesome. To fix this, you can (and should) go back to 404 or another 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 additional problems, you must enable rewrite_log on; , which will write the correspondence of the server error file at the notification level and help to find out the problems with the location matching.

+6
source

Source: https://habr.com/ru/post/1482410/


All Articles