I have successfully set up localisation on my website using php gettext, and a browser cookie is set when a visitor chooses their preferred language.
Whilst the pages are shown in the correct language, I want the URL to reflect the currently selected language by prefixing the URL with the language code (not the locale code).
This is what my htaccess file looks like at the moment:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^en(/?$|/(.*)) $1?locale=en_GB [QSA,DPI,L]
RewriteRule ^fr(/?$|/(.*)) $1?locale=fr_FR [QSA,DPI,L]
RewriteRule ^de(/?$|/(.*)) $1?locale=de_DE [QSA,DPI,L]
RewriteRule ^es(/?$|/(.*)) $1?locale=es_ES [QSA,DPI,L]
RewriteRule ^ru(/?$|/(.*)) $1?locale=ru_RU [QSA,DPI,L]
Let’s say a visitor clicks on the French language link on the homepage, the URL displayed to the visitor is mysite.com/fr and the language changes to French.
If they then click on the link for page1.php the URL changes to mysite.com/page1.php and the French version of Page 1 is displayed.
I would like the URL to be shown as mysite.com/fr/page1.php.
I’ve tried adding the following lines to htaccess, just below the RewriteCond lines, but I’m clearly doing it wrong:
RewriteCond %{HTTP_COOKIE} locale=([a-z]{2}\_[A-Z]{2}) [NC]
RewriteRule ^(.*)$ /%1/$1 [NC,L,QSA]
Note that in the lines above, I am attempting to prefix the URL with the entire locale code (e.g. fr_FR) whereas ultimately what I want is to prefix the URL with just the first two characters of the locale code (e.g. fr).
Thank you in advance.
I don’t think you should use .htaccess rewrites for this ..
http://mysite.com/page1.php you should figure you what language you want to show to him and redirect him, for instance to: http://mysite.com/en/page1.php – by looking at the browser language accept value for instance.
http://mysite.com/en/page1.php then you don’t have to do anything, you know which language to use.
I can strongly recommend you don’t use cookies for this. Many sites use cookies for this for absolutely no purpose at all, all they do is send you to the page in whatever language you selected. Completely infuriating if you don’t accept cookies by default (which everyone should).
Keep in mind that all your links on your site will always have the language as part of their URL, because if they don’t you’re back to situation 1 and your user might get switched back to the default language. Using a cookie here will only complicate matters, what if you really did want to switch to the French site after using the English site for a bit?
I guess the bottom line is: don’t use cookies in combination with your URL to identify a resource, it becomes very vague which resource exactly you’re referring to because cookies are not obvious. The only exception is of course when you’re doing some authentication stuff like user accounts and whatnot, but then lack of a cookie should always result in a ‘please log in’, not something that looks like the thing you wanted, but isn’t.