Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx aliases and dynamic directory names

Tags:

alias

nginx

I have spent muy tiempo on this and I can't get a solution. I need a way to point the same url but with different root directory to the same application. I don't want to use rewrites because the root directoy name has to be processed by the application and rewrite discards it.

http://www.host.com/a/ --> /var/www/html/project/
http://www.host.com/b/ --> /var/www/html/project/
http://www.host.com/c/ --> /var/www/html/project/

I've managed to configure in nginx an alias directory with a fixed name vdirectory and make nginx forward the request to fastcgi.

location /vdirectory {

      alias /var/www/html/project/;
      try_files $uri $uri/ /vdirectory/index.php;
      location ~ \.php$ {
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          include fastcgi_params;                       
          fastcgi_param SCRIPT_FILENAME $request_filename;
      }
}

The above works OK.

Since I don't want to use fixed root directory names but arbitrary ones, this is what I've managed so far:

location  ~ ^/(.?)$  {

      alias /var/www/html/project/;
      try_files $uri $uri/ /$1/index.php;
      location ~ \.php$ {
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          include fastcgi_params;                       
          fastcgi_param SCRIPT_FILENAME $request_filename;
      }
}

Needless to say, it returns 404. It is a good sign because it means regex has recognized the path, but the request isn't forwarded correctly.

The only difference between the working config and the wrong one is /vdirectory vs ~ ^/(.?)$

like image 940
Viktor Joras Avatar asked Dec 11 '25 17:12

Viktor Joras


1 Answers

alias works differently when inside a regular expression location block. See this document for details. You will need to capture the remainder of the URI and append that to the alias value. For example:

location ~ ^/(?<prefix>[^/]+)/(?<name>.*)$ {
    alias /var/www/html/project/$name;

    if (!-e $request_filename) { rewrite ^ /$prefix/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include fastcgi_params;                       
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

I avoid using try_files and alias within the same block due to long term issues. See this caution on the use of if.

like image 137
Richard Smith Avatar answered Dec 13 '25 06:12

Richard Smith