Issue with Removing Language Prefix on Front Page and Specific URLs in a Multilingual Context

Created on 9 October 2024, 2 months ago

Issue with Removing Language Prefix on Front Page and Specific URLs in a Multilingual Context

Hi everyone,

I'm currently working on a multilingual Drupal 10.3 site with two languages: French (fr) and English (en). All my pages are currently prefixed with the language code, for example:

  • /fr/actualites for news in French
  • /en/news for news in English

My site is configured to use the language prefix in the URL (which is standard for multilingual setups). However, I have a specific requirement where I need to:

  1. Remove the language prefix for the front page (<front>).
  2. Exclude the language prefix for API URLs that start with /api.

What I've Tried:

I created a custom language negotiation plugin using the LanguageNegotiationMethodBase interface and added logic to exclude certain paths from language negotiation. The idea was that if the path matches the front page (/) or any API URL (/api/*), the language prefix should not be added. Here’s a simplified version of the code I’m using:

public function getLangcode(?Request $request = NULL) {
  // Retrieve the list of excluded paths from the configuration.
  $excluded_paths = \Drupal::config('general_config.language_negotiation_excluded_url')->get('excluded_paths');
  
  if ($request) {
    $path = $request->getPathInfo();
    
    // If the current path matches any excluded patterns, return the default language code.
    foreach ($excluded_paths as $excluded_path) {
      if ($this->matchPath($path, $excluded_path)) {
        return \Drupal::languageManager()->getDefaultLanguage()->getId(); // Return default language
      }
    }
  }
  
  return parent::getLangcode($request); // Otherwise, fallback to the default language negotiation
}

The plugin is registered correctly, and I’ve added a configuration form to manage the excluded paths from the admin interface.

The Problem:

Despite this plugin, the URLs / (front page) and /api/* still have the language prefix, for example:

  • /fr and /en for the front page.
  • /fr/api/ or /en/api/ for API routes.

What I want is for these specific paths to not have a language prefix, like:

  • / for the front page without /fr or /en.
  • /api/* for API routes without /fr/api/ or /en/api/.

I’d appreciate any suggestions or guidance you might have! Thank you very much for your help.

Things I’ve Checked:

  • The excluded paths are correctly set in my configuration form.
  • The getLangcode() method seems to be called properly, but the expected changes are not reflected in the output.

Thanks for your help!

💬 Support request
Status

Active

Version

10.3

Component

language.module

Created by

🇫🇷France pgshehata

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024