Rewriting domain.com to domain.com/en/

I have a bilingual website with English is at domain.com/en/ and Italian at domain.com/it/

If someone visits domain.com they are initially redirected to domain.com/en/ using a PHP header() function.

I’m now wondering if this is the most effective way of achieving this.

I know I can use:

RewriteRule ^$ /en/ [L]

in my .htaccess file to map the home page to the /en/ directory, but if I then try to navigate to (say) about.php I end up at domain.com/about.php which gives me a 404 error. I’m pretty crap with RewriteRules and don’t want to make /it/ inaccessible.

Why do you do this with htaccess?

I would prefer you write a very small .php or JavaScript file which takes the client language and moves to the required language instead of always directing to English.

For example something Ike this


<?php
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    $acceptLang = ['fr', 'it', 'en']; 
    $lang = in_array($lang, $acceptLang) ? $lang : 'en';
    header('Location: /'.$lang.'/Index.php');

?>

1 Like

I haven’t used that method for language, but my gut tells me that if I did, I would write the url for about.php correctly as example.com/it/about.php in my navigation (i.e. by checking the current language while displaying the nav items) rather than trying to fix it when the page comes in.

2 Likes

Thanks @Thallius and @tracknut. The reason for thinking about using htaccess is that (I think) it doesn’t require an additional HTTP request.

However, I have my Sunday brain in at present and probably need to wait till tomorrow to think about this more deeply.