3

I'm running several SPAs in separate folders together with some static files. The structure is as follows:

|
|- index.html
|- foobar.html
|---- SPA1/
|     |- index.html
|     |---- SPA1_1/
|           |- index.html
|---- SPA2/
      |- index.html

The expected behavior is to:

  • serve all /SPA1/SPA1_1/foo/bar with SPA1/SPA1_1/index.html
  • serve all SPAx/foo/bar with SPAx/index.html
  • serve /not_exist with /index.html
  • serve /foobar.html with /foobar.html

In short, I want nginx to try the following paths in order:

  • $uri
  • $uri's closest parent

Is there any way to achieve this without specifying rules for each SPA directory?

lz96
  • 131
  • 5
  • Workaround: `try_files $uri $uri/ $uri/../ $uri/../../`? – lz96 Jul 12 '17 at 06:56
  • Note that this behavior (serving the same content for multiple urls) will decrease your ranking in search engine results. I'd highly recommend not to do this. – Gerald Schneider Jul 12 '17 at 06:59
  • @GeraldSchneider Thanks for your notification. In my case `SPAx` are all management systems built with HTML5 history API which are not exposed to spiders. The main pages are `/foobar.html` `/index.html` – lz96 Jul 12 '17 at 07:29

1 Answers1

2

You could recursively rewrite the URI by removing a directory path each time, until the index.html file is located. This would be an internal loop, and no external redirection would take place.

For example:

location / {
    try_files $uri $uri/index.html @rewrite;
}
location @rewrite {
    rewrite ^(.*)/.+ $1/ last;
}
Richard Smith
  • 12,834
  • 2
  • 21
  • 29
  • The problem of this option is that nginx limits internal redirects to 10 cycles. See http://nginx.org/en/docs/http/ngx_http_core_module.html#internal – joruro Jun 27 '18 at 06:29