.htaccess to determine the language

I have a problem with .htaccess my simplified file server structure is as follows:

/index.php /signup.php 

I need to work with virtual URLs to handle a language switch:

 www.mydomain.com/en/signup.php www.mydomain.com/de/signup.php 

so my .htaccess should check if url / en / or / de / contains and translate it, for example. /signup.php?language=de

basically they say it should strip the language tag, but preserve the rest of the folder structure.

it should work both on my local xampp and on my real server. any ideas? thanks

+8
.htaccess mod-rewrite
source share
1 answer

What have you tried? Something like the following should work:

 RewriteRule ^/(en|de)/(.*)$ $2?language=$1 [L] 

The meaning is pretty obvious: take the second match ( $2 ), this is what happens after the second slash in the URL, put ?language= after it, and then the first match ( $1 ), that is, between two two slashes - provided that it is one of en or de . If you want to map something (not just en or de ) as a language, then change the rule to:

 RewriteRule ^/(.+?)/(.*)$ $2?language=$1 [L] 

Please note :: ? in the first group will make a stop match with the first slash, so you wonโ€™t rewrite, for example.

 /en/subdir/pippo.php 

to

 pippo.php?language=en/subdir 

but rather

 subdir/pippo.php?language=en 

If in doubt, the Apache website has excellent documentation .


Edit: default language

To make all other requests (i.e. URLs starting with /en/ or /de/ ) redirected to the default language (say en ), you must first know the language prefixes that you want to recognize, and then use the following rules: below I assume that there are three -3 languages โ€‹โ€‹with the codes en , de and fr :

 RewriteEngine On RewriteBase / RewriteRule ^(en|de|fr)/(.*)$ $2?language=$1 [L,QSA] RewriteRule ^(.*)$ $1?language=en [L,QSA] 

If you do not determine the exact language specified in the first RewriteRule (for example, using my previous solution to โ€œany languageโ€), language detection may fail on the embedded pages. It is important that the rules be in that order, because the first one matches the pages with the language code, and then exits, and the second only if the first one does not match.

+12
source share

All Articles