AdamGold
AdamGold

Reputation: 5051

Create different URLs for different languages with htaccess

I am trying to create different URLs for different languages, for example http://localhost/shift/en without "en" being an actual folder (shift is an actual sub folder). I want the 'en' to be a variable I can use in my PHP code. Here is how my htaccess looks like:

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /shift/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ public/index.php [QSA,L]

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

Here's my PHP code:

var_dump($_GET['lang']);

When I go to http://localhost/shift/en it gives me a 404 and a PHP error: "undefined index: lang".

Upvotes: 0

Views: 65

Answers (1)

user5831063
user5831063

Reputation:

You need to edit your .htaccess like this-

RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?lang=$1 RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?lang=$1

and the index.php:

echo $_GET['lang'];

If the url is- http://example.com/en, then the output will be- en

You can do the other things then, with the language.

If you want to give different versions of the page, I recommend you using a page for each language and include them if a language is asked for in the url.

For example- If someone types http://example.com/en, in the index.php you need to do this-

 if($_GET['lang']=="en") {
     $_SESSION['language']="en"; //Adding a session makes your life easier
     include("en.php");
 //everything else
    }

I have updated the rewrite rule. Check it out.

Upvotes: 1

Related Questions