Handle languages in .htaccess

I want to solve the next problem:

1) When entering the url without language, use English language as default example:

http//localhost/plants/ or http//localhost/plants

or

http//localhost/plants/shop/accessories

2) When entering the url with language, pass that parameter as the language to use example:

http//localhost/plants/es/shop/accessories

or

http//localhost/plants/es/ or http//localhost/plants/es

So far I have tried:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(en|es)/(.*)$ index.php?url=$2&lang=$1 [L,QSA]

RewriteRule ^(.*)$ index.php?url=$1&lang=en [L,QSA]

If I comment the first RewriteRule and enter any url it works fine but always using the en language.

If I comment the second RewriteRule and I use a url with the language:

http//localhost/plants/es/

or

http//localhost/plants/es/shop/accessories

It works fine, but it doesn't set the default language to English when is not given.

Any idea why it doesn't work when I leave the two rules?

Thanks

Ps: I have removed the : after http

Upvotes: 1

Views: 264

Answers (3)

Panama Jack
Panama Jack

Reputation: 24448

If plants is your document root, you should be able to use this rule.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} !/(en|es)
RewriteRule ^(.*)/?$ index.php?url=$1&lang=en [L,QSA]
RewriteRule ^(en|es)/?(.*)/?$ index.php?url=$2&lang=$1 [L,QSA]

Let me know how it works for you.

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80629

Put the following htaccess file inside the /plants directory:

RewriteEngine On
RewriteBase /plants

RewriteCond %{REQUEST_URI} !^/plants/e[ns](/|$) [NC]
RewriteCond %{QUERY_STRING} !lang=e[ns] [NC]
RewriteRule ^.*$ /plants/en/$0 [R=301,L]

RewriteRule ^(e[ns])/(.*)$ index.php?url=$2&lang=$1 [NC,L,QSA]

If the above still doesn't work, update your own approach to something like:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

RewriteRule ^(en|es)/(.*)$ index.php?url=$2&lang=$1 [L,QSA]
RewriteRule ^(.*)$ index.php?url=$1&lang=en [L,QSA]

Upvotes: 1

Found a solution doing this:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(en|es)/(.*)$ index.php?url=$2&lang=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.*)$ index.php?url=$1&lang=en [L,QSA]

How can I improve this? It feels wrong I have to write twto time the same Cond

Upvotes: 1

Related Questions