Daniel Hollands
Daniel Hollands

Reputation: 6681

nginx redirects - how can I optimise my code?

I've got the following config (which works) in nginx:

location /de-de/sitemap.xml {
    try_files $uri /sitemaps/de-de/sitemap.xml;
}

location /en-ae/sitemap.xml {
    try_files $uri /sitemaps/en-ae/sitemap.xml;
}

location /en-de/sitemap.xml {
    try_files $uri /sitemaps/en-de/sitemap.xml;
}

location /en-gb/sitemap.xml {
    try_files $uri /sitemaps/en-gb/sitemap.xml;
}

location /en-us/sitemap.xml {
    try_files $uri /sitemaps/en-us/sitemap.xml;
}

This is because requests from the outside will be looking for (say) /en-gb/sitemap.xml, but the actual file for said sitemap actually exists in /sitemaps/en-gb/sitemap.xml.

Now, like I said before, this works, but I can't help but think it could be optimised (i.e using some type of matching rule, rather than listing each of the store codes individually??) but I've not had much luck making it work.

Plus I'm not sure if the try_files command is the best for this purpose.

Thank you.

PS, it is only the sitemap.xml files that I want to target, all other files that exist within that path should be served as usual.

Upvotes: 0

Views: 72

Answers (1)

Cole Tierney
Cole Tierney

Reputation: 10324

You could try using a back reference to the language element of the path:

location ~ "^/([a-z]{2}-[a-z]{2})/sitemap.xml$" {
    try_files $uri /sitemaps/$1/sitemap.xml;
}

Upvotes: 1

Related Questions