I have really simple nginx configuration with 3 locations inside. Each of them have it's own root directory + I should be able to add another in the future easily.
What I want:
Request /admin
=> location ^/admin(/|$)
Request /admin/
=> location ^/admin(/|$)
Request /admin/blabla
=> location ^/admin(/|$)
Request /client
=> location ^/client(/|$)
Request /client/
=> location ^/client(/|$)
Request /client/blabla
=> location ^/client(/|$)
Request /blabla
=> location /
Request /admin-blabla
=> location /
Request /client-blabla
=> location /
Actual result:
All requests goes to location /
.
I tried many different suggestions from docs, stackoverflow and other sources using different combinations of aliases, try_files, roots and regexes, but nothing worked for me.
Only when I tried to use just return 200 'admin';
and return 200 'front'
it worked as intended.
Minimal config:
server {
listen 80;
index index.html;
location / {
root /var/www/html/www_new/front;
try_files $uri $uri/ /index.html;
}
location ~ ^/admin(/|$) {
root /var/www/html/www_new/admin;
try_files $uri $uri/ /index.html;
}
location ~ ^/client(/|$) {
root /var/www/html/www_new/client;
try_files $uri $uri/ /index.html;
}
}
Directory structure:
Thank you
When you change the root it'll still include the directory name, so what you want to do is only set the root for location /
. You also don't need any additional regex on /admin
as the location modifier ~
already tells nginx 'anything starting with'.
This works for your use case:
server {
listen 80;
index index.html;
location / {
root /var/www/html/www_new/front;
try_files $uri $uri/ /index.html;
}
location ~ ^/admin {
root /var/www/html/www_new; # the directory (/admin) will be appended to this, so don't include it in the root otherwise it'll look for /var/www/html/www_new/admin/admin
try_files $uri $uri/ /admin/index.html; # try_files will need to be relative to root
}
}