Forwarding to the chosen language at the main page of the website

Currently, I'm in the process of developing a multilingual website using Hugo with the support of a multilingual theme called Ananke. For this project, I have added content in two different languages and configured the necessary settings in the configuration file as shown below:

defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true

In addition to that, I have defined the two languages with their respective base URLs like so:

[languages]
  [languages.en]
    baseURL = "https://example.com/en"
    weight = 100
  [languages.nl]
    baseURL = "https://example.com/nl"

During the generation process by Hugo, the expected directories for each language are created successfully. However, when deploying the website and accessing the base URL example.com, no HTML content is generated at that location.

To address this issue, one solution would be to manually add an index.html file at the root of the site with a JavaScript script that redirects users based on their preferred language setting:

<!DOCTYPE html>
<html lang="en-us">
  <head>
   <script type="text/javascript>

      var languageCookie = getCookie("preferredLanguage")

      if (languageCookie) {
         var language = languageCookie
      } else {
         var language = navigator.language || navigator.userLanguage;
      }

      if (language == "nl") {
         window.location.href = "https://example.app/nl"
         document.cookie = "preferredLanguage=nl"
      }
      else {
         window.location.href = "https://example.app/en"
      }

      function getCookie(name) {
         const value = `; ${document.cookie}`;
         const parts = value.split(`; ${name}=`);
         if (parts.length === 2) return parts.pop().split(';').shift();
      }

   </script>
  </head>
</html>

However, I am looking for a way for Hugo to automatically generate this HTML instead. Is there a method to specify a separate page or JavaScript code that is independent of the language? Any guidance on how to achieve this would be greatly appreciated.

Answer №1

Creating the main index.html

When I visit example.com, I don't see any content because there is no HTML generated for that specific URL.

The issue may arise from using the same baseURL for multiple languages. The configuration documentation suggests this setting is intended for specifying different hostnames rather than paths on the same domain. If you are trying to use it for different domains, then this might not be the right approach!

It could potentially be a bug in the system, but further investigation is necessary.

Default Setup

If you have only one domain, the following configuration should work:

DefaultContentLanguage = "en"
defaultContentLanguageInSubdir = true

output= ["html"]

[languages]
  [languages.en]
    languageName = "English"
    contentDir = "content/en"
    weight = 10
  [languages.nl]
    languageName = "Nederlands"
    contentDir = "content/nl"
    weight = 20

This setup should result in a directory structure like the following:

public
├── index.html
├── en
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
├── nl
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
└── sitemap.xml

The main index.html file should already include the necessary redirect logic, utilizing a <meta> refresh tag redirecting to the default language page.

This setup should resolve the issues with the primary index.html without requiring additional modifications.

Platform-Specific Solutions

Depending on your hosting platform, consider providing custom redirect rules through methods such as creating a Netlify's _redirects file.

Language-Independent Elements

How can I implement a separate page or JavaScript functionality that is independent of language?

If you require custom code on the root index.html, it may pose challenges. However, you could try:

  1. Implement the first suggestion to ensure an index.html exists;
  2. Alternatively, embed the JavaScript directly within your layout files.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the empty gap to appear during animated transitions between two 'div' elements?

Is there a way to eliminate the white space in between elements during animation? Should I wrap both divs into another div to achieve this? I am using position-top to adjust my div animations. Could this be causing the issue? What other methods can you s ...

Kendo dropdown list won't trigger the change() event

I am using a Kendo DropDownList to load data from JSON. However, the onchange event of the dropdownlist is not firing. <input class="ddEmailInitiation" /> <script>$(".ddEmailInitiation").kendoDropDownList ({ dataTextField: "Type", dataSour ...

Is it more effective to specify the class within the selector when using jQuery to remove a class?

Does including the class in the selector when removing a class using jQuery have any impact on performance or best practices? I'm curious if there will be any noticeable difference. For example, do you include it like this: $('#myList li.classT ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

The content is not being displayed on the webpack dev server

Encountering an issue while running the webpack dev server with npm start command. Upon running the command, the output displayed is as follows: ➜ directory git:(staging) ✗ npm start directory @1.0.0 start directory BUILD_DEV=1 BUILD_STAGING=1 ./n ...

the angular-ui-tinymce directive allows for seamless image uploads using a file browser

Utilizing jQuery, we have the ability to incorporate local images into the tinymce editor similar to what is demonstrated in this jsfiddle, by following the guidelines provided in the documentation. The Angular module for tinymce can be found at angular-u ...

On mobile devices, the code "location.assign(url)" may occasionally redirect to an incorrect URL, despite functioning correctly in the majority of instances

After setting up a page with a timeout that should automatically redirect to a specific URL after 60 minutes, I encountered an issue where the redirection sometimes leads to a loss of parameters in the URL. The JavaScript code added for this purpose is set ...

Customizing a carousel in Next JS to loop through items and control their visibility

I've created a custom Next JS carousel that tracks the current slide index and displays an image or video accordingly. However, it appears that because the carousel is set to autoplay and each slide is removed and readded every 6 seconds, the page dow ...

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

Having difficulty performing raycasting on a singular object within a group in three.js to trigger an animation

Having issues with raycasting into a group in my three.js project. The goal is to trigger animations using TweenMax on object click. However, the problem arises when clicking on an object with another object behind it, causing both animations to be trigge ...

How can I load 3-D models in three.js by specifying file content instead of the file path?

I'm looking to develop an interactive online model viewer that allows users to easily upload and view models without having to manually edit the source code. Unfortunately, most browsers restrict access to file paths, but can still read file contents. ...

Looking for an alternative method since jQuery has deprecated the use of '.toggle()' function

After jQuery deprecated the .toggle() method, I have been searching for a new and simple solution to implement a "Read more" button that slides down a paragraph while changing text to "Read less". Below is the code I have put together: var moreText = "Re ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...

Unable to interpret encoded json information

I'm currently developing a basic chat system using PHP and jQuery with Ajax, but I've encountered an issue when trying to display a JSON encoded string through the ajax callback function. Below is the code for the ajax request: $.ajax({ url: ...

What is the best way to adjust the browser size within a Protractor Test?

Is there a way to maximize the browser size before running the Protractor tests? I've heard about using the beforeAll() function, but I'm not sure how to set the size. Any suggestions? ...

Tips for including items in a list nested within a dictionary using JavaScript

I'm currently working with a JavaScript dictionary and I need to insert an element into a list that belongs to a specific key within the dictionary. Check out the code snippet below: lines = [ [1,2], [2,4], [2,3], [3,5] ]; nodes = [ ...

Troubleshooting problem with chat messages due to Firestore snapshot limit or limitToLast issues

I'm currently developing a chat application using React Native with Firestore integration. To retrieve the latest 25 messages in the Chat screen, I am ordering them by timeSent and limiting to last 25 items: firestore .collection('group') ...

Understanding the rationale for rendering Views with vuex dependencies in vueJS

I'm facing an issue with my API call in App.vue that populates the vuex store's state. The Home.vue component displays images based on the store's state, but console errors are thrown before the state is populated. I'm unsure about the ...

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...