Ad

Switching Language With .htaccess

- 1 answer

I want to add another language to my website (an app written in PHP 7). I found out, good SEO practices say that every page on my site should be accessible from differend URLs, depending on the language.

Currently my .htaccess looks something like this:

RewriteEngine on
Options +FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([a-zA-z0-9-]+)$ $1.php [NC,L]

So when user types in (or clicks a link) http://example.com/contact they get page contact.php (if exists). What I want to achieve is, to redirect http://example.com/en/contact to the very same file contact.php, but with $_GET argument and still redirecting /contact to contact.php (without this argument). I thought that would be:

... everything from above code sample and then:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^en/([a-zA-z0-9-]+)$ $1.php?lang=en [NC,L]

But it doesn't work. Any ideas why and how to make this work?

Ad

Answer

Last condition checks that en/file.php exists, which is never the case. That's why the rule is never met. Either you remove it (but it will be applied even on nonexistent files) or you use this workaround by rewriting the faulty condition

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^en/([^/]+)$ /$1.php?lang=en [NC,L]

To be more complete, you can also redirect users that try to access /contact.php?lang=en directly (better for SEO). Here is how your final htaccess should look like

RewriteEngine On

# if url is /file.php?lang=en and file exists then redirect to /en/file
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} \s/([^/\s\?&]+)\.php\?lang=en\s [NC]
RewriteRule ^ /en/%1? [R=301,L]

# if url is /en/file and /file.php exists then internally rewrite to /file.php?lang=en
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^en/([^/]+)$ /$1.php?lang=en [NC,L]

Note: the above code is specific to en language, but you can easily adapt it to multiple languages

Ad
source: stackoverflow.com
Ad