How to make a site with pretty URLs with i18n?

253 Views Asked by At

First of all, I read this issue which seemed to me to correspond to solving my problem but I don't understand it after several rereading and testing: https://github.com/i18next/react-i18next/issues/325 (maybe because I'm not using react)

I also tried this one (with .htaccess) : https://github.com/i18next/i18next/issues/144

But it gives a 404 error.

I recently tried to make a site with i18next, which works fine but I would like to be able to add nicer URLs with country codes.


Example instead of (which change the language):

https://www.mywebsite.com/index.html?lng=fr-BE

this

https://www.mywebsite.com/fr-BE


Knowing that I can't use back-end language like PHP, etc... that I use an Apache web server and that I only use i18next with jquery.i18next.

To describe my problem a little more in depth, how could I make sure that when a user arrives on any page it adds the country code? What if it already has a country code in the URL, change the user's language?

And above all, is it possible?

Thank you for reading my issue and hoping that you can help me with my problem. :)

P.S.: Please excuse me for my English

1

There are 1 best solutions below

0
On

Totally possible.

So first in your .htaccess file you'd want to have something like this:

RewriteEngine On
RewriteRule ^(\w+)\/?([\w\-]+)?$ $1.html?lng=$2

This would rewrite a URL of the form

www.example.com/index/fr-BE to www.example.com/index.html?lng=fr-BE

So I'm using this approach because you may want to consider the language parameter optional and default it to a certain value. And this rule will also redirect

www.example.com/some_page to www.example.com/some_page.html

That's that with the friendly URLs. Now for the part of getting the language param from the query string. Without using a server side language (like PHP) you can't be using the value from 'lng' parameter, but following the guide from here you can use window.location.pathname to get the language string, when present.

So for a URL of the form www.example.com/index/fr-BE, you could be using the following code:

let params = window.location.pathname.split('/').slice(1);

if(typeof params[1] !== 'undefined') {
    console.log(params[1]); // <-- should be 'fr-BE'
    i18next.setLng(params[1]);
}

Hope this helps.