Search code examples
php.htaccessmod-rewriteparametersmultiple-languages

Redirect language query string to subdirectory for better SEO


I'm developing a web site that supports multiple languages (english and spanish) in PHP using parameters like this:

www.website.com/contact?lang=en
www.website.com/contact?lang=es

Yes, without extension .php... I know that is a bad practice, so I want to have this:

www.website.com/en/contact
www.website.com/es/contact

I read other posts here in stackoverflow but, I don't want to use a PHP framework, and I read that I have to use Mod Rewrite (again because I already use it for remove the extension). In fact, I read this post (and others too), but nothing works.

When it is done, I read in google pages that I have to use:

<link rel="alternate" href="http://www.website.com/" hreflang="x-default" />

is this correct?

Thanks

EDIT 1:

The content of my .htaccess is:

RewriteBase /

#Prevent directory listing
Options All -Indexes

#Disable Etags
Header unset ETag
FileETag None

#Prevent viewing of .htaccess
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
</Files>

RewriteEngine on

#Redirect non-www/www
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#RewriteCond %{HTTPS} off
#RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
#RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Options +FollowSymlinks -MultiViews
#Rewrite url
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html

RewriteCond %{REQUEST_FILENAME} -f  [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]

RewriteRule ^([^/]+)/([^/]+)  /$2?lang=$1 [L,NC,QSA]

Solution

  • This should be your full .htaccess with a new rule to redirect lang specific URLs:

    #Disable Etags
    Header unset ETag
    FileETag None
    
    #Prevent viewing of .htaccess
    <Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    </Files>
    
    Options All -Indexes -MultiViews
    RewriteEngine on
    RewriteBase /
    
    #Redirect non-www/www
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    
    # redirect /contact?lang=en to /en/contact
    RewriteCond %{THE_REQUEST} /+([^?]+?)(?:\.php)?\?lang=([^\s&]+) [NC]
    RewriteRule ^ /%2/%1? [R=301,L,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+?)/?$ $1.html [L]
    
    RewriteCond %{REQUEST_FILENAME} -f  [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule . - [L]
    
    RewriteRule ^([^/]+)/([^/]+) $2?lang=$1 [L,QSA]