Hafez Divandari
Hafez Divandari

Reputation: 9029

How to use matched location as a variable in Nginx server block?

I have a nginx server configuration like this:

server {
  listen 80;
  listen [::]:80;
  root /var/www/html;
  index index.php index.html index.htm;
  server_name example.com www.example.com;

  location /project1/public {
    try_files $uri $uri/ /project1/public/index.php?$query_string;
  }

  location /project2/public {
    try_files $uri $uri/ /project2/public/index.php?$query_string;
  }

  location /project3/public {
    try_files $uri $uri/ /project3/public/index.php?$query_string;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  }
}

and it works. But when I try to use regex (following code) to do this dynamically, it downloads the URL instead of showing it in the browser.

server {
  listen 80;
  listen [::]:80;
  root /var/www/html;
  index index.php index.html index.htm;
  server_name example.com www.example.com;

  location ~ ^/([^/]+)/public {
    try_files $uri $uri/ /$1/public/index.php?$query_string;
  }

  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  }
}

Any idea?

Upvotes: 0

Views: 439

Answers (1)

Moema
Moema

Reputation: 863

Try changing the order of your location blocks.

If you check the order/priority of the location blocks in Nginx Docs there are two rules which are important for your config:

  1. If Nginx finds a conventional location block (like /project1/public), it does not stop searching and any regular expressions and any longer conventional blocks will be matched first

    --> So in your first config, Nginx first fires your php-regex location and then it executes the try_files

  2. Regular expressions are checked in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used.

    --> In your second config, your php-regex is never used since the try_files is found first

Upvotes: 1

Related Questions