1

I need help for rewrite url via htaccess by adding language. I found this example and work fine: .htaccess language redirects with SEO-friendly URLs

However I need something more generic, for avoid to add all language code on htaccess.

Something like:

RewriteCond %{HTTP:Accept-Language} ^([a-zA-Z]{2}) [NC]
RewriteRule ^$ /$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^.*$ index.php [L]

I would like also know that maybe I can do this via PHP? Or for SEO is better use htaccess? Or it's the same? But maybe this is another question in relation with SEO...

0
RewriteCond %{HTTP:Accept-Language} ^([a-zA-Z]{2}) [NC]
RewriteRule ^$ /$1/ [L,R=301]

Almost, you just need to use %1 instead of $1, as a backreference to the last matched CondPattern (RewriteCond directive pattern), as opposed to the RewriteRule pattern (which is what $1 refers to).

You also don't need the NC (nocase - case insensitive match) flag if you are specifying lower and uppercase in the pattern, or remove uppercase from the pattern. In other words:

RewriteCond %{HTTP:Accept-Language} ^([a-z]{2}) [NC]
RewriteRule ^$ /%1/ [L,R=301]

Clear your browser cache before testing.

I would like also know that maybe I can do this via PHP?

Well, you could, but it's more efficient to do this in the Apache config. However, if you needed to do something more complex then maybe PHP would be better. For instance, by testing ^([a-z]{2}) you are only checking the first language (which you assume is the preferred language). However, the Accept-Language header is quite complex as it can contain multiple languages with different weights (eg. Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5). If you needed to parse this header then PHP would be preferable.

Or for SEO is better use htaccess?

For SEO it makes no difference.

  • Thank you! I understand what you mean about accept-language. I think that will be better to use PHP to check also if language exist. I just worry about SEO, but if doesn't matter for SEO, then I think PHP is fine. Why you said that is more "efficient" using htaccess? It's just a redirect that is done.... Thanks – user2011250 Mar 15 '17 at 6:33
  • .htaccess (an Apache config file) is processed at the very start of the request. PHP runs much later. And by the time you do the redirect (in PHP) many other things have probably been loaded and processed, consuming more resources and generally taking time. Admittedly, the difference is probably minimal for a single request, but x100, x1000 requests etc. (depending how heavy your CMS is) could be measurable. – MrWhite Mar 15 '17 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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