How to serve files according to the header accept-language

How to serve files based on the accept-language header? I know that the header_regexp directive can be used for request matching by regular expression, but the selection of a language follows a list of preferred locales, like the example below.

An example of a list of accepted languages, sent by the browser:

accept-language: en-US, en;q=0.9, pt-BR;q=0.8, pt;q=0.7

In that request, the semantic is: "The order of preference is English US, if not present, try the Portuguese BR ". The server can select a default language, let’s say English, if any of the requested languages are supported.

The request matchers can be done like:

@english {
  header Accept-Encoding *en-US*
  file {
      try_files /en_US/{path} 
  }
}

@portuguese {
  header Accept-Encoding *pt-BR*
  file {
      try_files /pt_BR/{path} 
  }
}

… But I don’t know how to elaborate the selection logic according to the list of languages from the accept-language header.

There is no inbuilt mechanism for Caddy to parse the Accept-Language header into a list of priorities to select the highest available.

That’s some non-trivial logic. It could possibly be done with some regular expressions and a single large try_files, but it will get complex quite fast, I imagine.

It might do a lot better as a custom handler module, maybe - one you could supply your list of supported languages and their file paths, and would rewrite as appropriate after parsing the header into a list in order.

1 Like

What you’re looking for is “content negotation” and there is an open issue / TODO for that: v2: Content negotiation · Issue #2665 · caddyserver/caddy · GitHub

I’m still not really sure how it will be implemented.

2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.