Wolfram Research

Function Repository Resource:

HTTPLanguageRedirect

Source Notebook

Redirect user from root to supported locale directory based on “Accept-Language” header

Contributed by: Cody Woodard

ResourceFunction["HTTPLanguageRedirect"][languages,options]

returns HTTPRedirect, which sends user to appropriate supported locale directory.

Details and Options

This function supports the following options:
"FallbackLanguage" "en" default locale
"PreferredRegion" {} replace generic language with region variant

Examples

Basic Examples

Assume you have two localized versions of a site:

In[1]:=
SetCloudDirectory["/HTTPLanguageRedirect"]
Out[1]=
In[2]:=
CloudDeploy["Hello", "en/index.nb", Permissions -> "Public"]
Out[2]=
In[3]:=
CloudDeploy["Hola", "es/index.nb", Permissions -> "Public"]
Out[3]=

Apply CloudDeploy to the HTTPLanguageRedirect at index.nb:

In[4]:=
CloudDeploy[ResourceFunction["HTTPLanguageRedirect"][{"en", "es"}], CloudObject["index.nb"], Permissions -> "Public"]
Out[4]=

Now send users to the root of your site:

In[5]:=
URL[First[CloudObject[""]] <> "/"]
Out[5]=

Based on their browser settings, they will be automatically redirected to the correct localized version:

In[6]:=
Association[
  URLRead[HTTPRequest[
    CloudObject[""], <|"Headers" -> <|"Accept-Language" -> "en"|>|>], "Headers", FollowRedirects -> False]]["location"]
Out[6]=
In[7]:=
Association[
  URLRead[HTTPRequest[
    CloudObject[""], <|"Headers" -> <|"Accept-Language" -> "es"|>|>], "Headers", FollowRedirects -> False]]["location"]
Out[7]=

Scope

You may support multiple languages:

In[8]:=
ResourceFunction["HTTPLanguageRedirect"][{"en", "fr", "es", "de"}]

Options

If you are supporting regional variants, you should include the generic language and use the “PreferredRegion” option to rewrite the generic language to the preferred regional variant:

In[9]:=
ResourceFunction[
 "HTTPLanguageRedirect"][{"en", "fr", "en-ca", "en-us", "fr-ca"}, "PreferredRegion" -> {"fr" -> "fr-ca", "en" -> "en-ca"}]

The “FallbackLanguage” option returns a default language if none are applicable:

Possible Issues

This function will redirect to a lowercase version of your supported languages:

In[10]:=
ToLowerCase[{"en-US", "en", "FR"}]
Out[10]=

The Wolfram Cloud currently only supports “index.nb” and “index.html” for base directory URLs.

Resource History

License Information