Dynamic nginx domain root path based on hostname?
Solution 1:
Why not just use:
server_name *.frameworks.loc;
root /var/www/frameworks/$http_host/public;
Solution 2:
Nginx config is not a program, it's a declaration. When you are using config like this:
server {
server_name ~^(.+)\.frameworks\.loc$;
...
set $file_path $1;
root /var/www/frameworks/$file_path/public;
}
There's no way to ensure that your set
directive will execute before root
.
But there's a trick with map
directive I like to use. It relies on fact that map
is evaluated before location
http {
map $http_host $rootpath {
~^(.?<mypath>+)\.frameworks\.loc$ $mypath;
default / ;
}
....
root /var/www/frameworks/$rootpath
}
Solution 3:
In addition to great DukeLion's answer, I needed to change line
~^(.?<mypath>+)\.frameworks\.loc$ $mypath;
to
~^(?P<mypath>.+)\.frameworks\.loc$ $mypath;
in my /etc/nginx/nginx.conf
file as suggested here.
Adding
root /var/www/frameworks/$rootpath
in /etc/nginx/sites-available/default
worked fine after that.