I have a multilanguage website with this structure http://www.url.com/en/
, http://www.url.com/it/
, http://www.url.com/pt/
etc. My problem now is that when you access the link url.com I will have 3 redirects.
http://url.com
http://www.url.com
http://www.url.com/en/
How can I do to have only 2 redirects? If you access http://url.com
to redirect to http://www.url.com/en/
In my htaccess file I have this lines.
RewriteCond %{HTTP_HOST} ^url.com [NC]
RewriteRule ^(.*)$ http://www.url.com/$1 [L,R=301]
This one redirects from url.com to http://www.url.com
. After this is redirected a php file script recognized the domain and it redirects again to /en/
$url= strpos($_SERVER['REQUEST_URI'],"/".$lang."/");
if($url!==0){ Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://www.url.com/en/" ); }
After that I have some conditions to check if you are in another language.
if($lang == "pt"){$langcheck = "pt"}
My links are created like this:
RewriteRule ^([_A-Za-z0-9-]+)\/$ index.php?page=index&lang=$1 [L]
So what should I write in htaccess to work this for each language. Because if I change the RewriteRule to url.com/en/
the other languages doesn't work anymore.
How to accomplish this depends upon where you get the language string from, how many languages you want to support, and how complex this interaction should be.
If it's just a couple of languages, and you want to use the browser settings for this, you might be able to use htaccess rewrites for this.
However, if you have more than just a few languages, want to let users select their own language in the site itself, or anything more complex than the above. Well, then you need to do everything in PHP.
This means removing the htaccess redirect for the missing "www" domain, then checking for this in the PHP code. Before, or after, you check for the language selected. Using both checks to determine the link to redirect to, before actually redirecting.
Meta example:
// We want all users to use the domain with www.
$redir = '';
if (substr ($url, 0, 3)) != 'www') {
$redir .= 'www.';
}
// If user has selected a different language, we need to redirect for that too.
if (!empty ($lang)) {
$redir .= "{$base_url}/{$lang}/";
}
// If $redir isn't empty, redirect the user.
// PS: Always remember to use `die()` after a `header()` redirect!