0

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.

ahron
  • 365
  • 3
  • 14
  • 1
    Simplest solution is to use `root /;` with `try_files $uri $uri.html /index.html;` and place it inside `location /products/ { ... }` – Richard Smith Oct 10 '22 at 06:51
  • 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? – ahron Oct 10 '22 at 07:21
  • 1
    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). – Richard Smith Oct 10 '22 at 08:51

1 Answers1

0

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
}
ahron
  • 365
  • 3
  • 14