1

I'm working on a Craft 4 project with five languages set up as separate sites. The primary site is configured to use 'en-GB' as the language and 'en' as the handle.

Currently, when I access the home page of my site using https://my-website.local/, it correctly displays the English site. The same happens when I use https://my-website.local/en/.

To avoid canonical issues caused by having duplicate pages under different URLs, I want to ensure that every page automatically includes the primary language handle ('en') in the URL, if one's not already present.

I haven't found a setting in Craft CMS that allows for this type of redirection. It seems I might need to handle this via .htaccess. I tried the following configuration:

RewriteCond %{REQUEST_URI} !^/(en|es|de|it|fr)/
RewriteCond %{REQUEST_URI} !^/(index\.php)
RewriteRule ^(.*)$ /en/$1 [R=301,L]

However, this approach leads to an incorrect duplication in the URL, such as https://my-website.local/en/en/ or https://my-website.local/en/fr, regardless of the RewriteCond conditions.

Does anyone have experience with a similar setup or suggestions on how to properly configure the .htaccess file to achieve this without causing URL duplication?

Example Sites

1 Answer 1

2

I think the issue is that your first RewriteCond only excludes the language prefix in the path with a trailing slash. The regex matches /en/ and /fr/, but not /en and /fr. To fix this, make the trailing slash optional:

RewriteCond %{REQUEST_URI} !^/(en|es|de|it|fr)/?

As an alternative, we handle this on the application layer. On a site with a similar site setup, we have this in our main Twig layout file:

{%- if craft.app.response.isOk and
    currentSite.primary and
    craft.app.request.fullPath|split('/')|first != 'en'
-%}
    {%- redirect siteUrl(craft.app.request.fullPath) 308 -%}
{%- endif -%}

This will redirect the primary site to the canonical URL if it's visited without the language prefix in the path. But it will not redirect any URLs that lead to a 404 page, which you can't do on the server.

Having the redirect on the application layer makes it part of the business logic, instead of the infrastructure. Probably not advisable if you're experiencing high server loads, as redirecting through the server is more efficient.

1
  • 1
    This is a lovely solution, thank you. I never considered how the redirects might have an effect on error page templates. I will be going with the Twig solution 👍 Commented Dec 8, 2023 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.