Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly use try_files when looking in two different directories for files to serve?

I'm quite new to Nginx so I might be misunderstanding of what try_files can do.

For my local development set up I have multiple installations that will each be accesible via their own subdomain. These installations are being migrated into a new folder structure but I still want to have the ability to support both at the same time. When pulled via git the new full path looks like this :

/home/tom/git/project/v3/[installation]/public/

The old structure goes 1 directory deeper namely as follows:

/home/tom/git/project/v3/[installation]/workspace/public

Where installation is variable according to the installation name and the /public folder will be the root for nginx to work from.

The root is determined by the subdomain and is extracted via regex like so:

server_name ~^(?<subdomain>[^.]+)\.local\.project\.test;

So far I've managed to get all this working for one of the folder structures but not both at the same time. My Nginx configuration for this local domain looks like this. Below is what I've tried but just can't seem to get working. As soon as I pass the @workspace named location as fallback for try_files it always defaults to 404.

index index.html index.htm index.nginx-debian.html index.php;

server_name ~^(?<subdomain>[^.]+)\.local\.project\.test;

root /home/tom/git/project/v3/$subdomain/public/;

location / {
        try_files $uri @workspace =404;
}

location @workspace {
        root /home/tom/git/project/v3/$subdomain/workspace/public/;
        try_files $uri =404;
}

I have also tried shortening the root and passing the following parameters to try_files

root /home/tom/git/project/v3/$subdomain;
location / {
        try_files /public/$uri /workspace/public/$uri =404;
}

But this still defaults to a 404, with a $uri/ as a third parameter there it will emit a 403 forbidden trying to list the directory index of the root.

I hope someone can provide some advice or an alternative as to how to approach this issue I am facing. If I need to provide additional data let me know,

Thanks in advance.

like image 223
Rimble Avatar asked Jan 01 '26 14:01

Rimble


1 Answers

The named location must be the last element of a try_files statement.

For example:

location / {
    try_files $uri @workspace;
}
location @workspace {
    ...
}

See this document for details.


The $uri variable includes a leading /, so your constructed pathnames contain a // which may be why they fail.

For example:

location / {
    root /home/tom/git/project/v3/$subdomain;
    try_files /public$uri /workspace/public$uri =404;
}
like image 130
Richard Smith Avatar answered Jan 04 '26 18:01

Richard Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!