Function Repository Resource:

HTTPLanguageRedirect

Source Notebook

Redirect a user from the root to a supported locale directory based on the "Accept-Language" header

Contributed by: Cody Woodard

ResourceFunction["HTTPLanguageRedirect"][languages,options]

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

Details and Options

The Wolfram Cloud currently only supports "index.nb" and "index.html" for base directory URLs.
ResourceFunction["HTTPLanguageRedirect"] supports the following options:
"FallbackLanguage""en"default locale
"PreferredRegion"{}replace generic language with region variant

Examples

Basic Examples (5) 

Set your cloud directory:

In[1]:=
SetCloudDirectory["/HTTPLanguageRedirect"]
Out[1]=

Assume you have two localized versions of a site:

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 (1) 

You may support multiple languages:

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

Options (2) 

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:

In[10]:=
ResourceFunction["HTTPLanguageRedirect"][{"fr", "es"}, "FallbackLanguage" -> "fr"]

Possible Issues (1) 

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

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

Version History

  • 1.0.0 – 10 July 2019

License Information