Score:0

Nginx: try_fiiles directive with variable from path

fr flag

I have set up a server block that looks like this:

root /var/www/platform

location / {
 index index.html;
}

location /contact {
 try_files $uri /contact.html;
}

This works fine. I can go to x.com/contact and the contact.html page loads.

Now I want to add a subdirectory products with files like product1.html and so on. When the user goes to x.com/products/product1 I want to load the html file.

Because the products subdir is within the platform directory, x.com/products/product1.html works fine with the current ^ setup. I just want to get rid of the need to have .html at the end.

So I try adding a location block

location /products/(product) {
 root /products;
 try_files /$1.html $1.html /index.html;
}

But obviously this doesn't work. Any help will be appreciated.

If there's another better (but still easy) approach, I'd love to know it too.

Richard Smith avatar
jp flag
Simplest solution is to use `root /;` with `try_files $uri $uri.html /index.html;` and place it inside `location /products/ { ... }`
Ahron avatar
fr flag
Thank you! So `$uri` is the part after the location.. saves a lot of trouble. Can you please explain briefly - what was wrong the way I tried?
Richard Smith avatar
jp flag
No. `$uri` is the current URI and includes the `/products` prefix, which is why you need to remove it from `root` within the `location /products` block. Your version would have worked if you used the correct syntax for a [regular expression `location`](http://nginx.org/en/docs/http/ngx_http_core_module.html#location).
Score:0
fr flag

Richard basically answered the question in the comments (I am writing this to remove the question from the list of unanswered ones). The solution that worked is adding this location block instead:

location /products/ {
 try_files $uri $uri.html /index.html
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.