skip to Main Content

On my custom CMS I have a page with link like this:

www.mywebsite.com/index.php

Now I’m trying to use multilingual pages, so I’m testing on the index page. With MySQL and language switcher I’m successfully getting the content from the chosen language.

So, the link becomes like this on English and German:

www.mywebsite.com/index.php?lang=en
www.mywebsite.com/index.php?lang=de

With this htaccess code I’m removing the .php and index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

So the link becomes like this:

www.mywebsite.com/?lang=en
www.mywebsite.com/?lang=de

For SEO purpose I want to remove the parameter ?lang=en or ?lang=de and put /en or /de, so the URL to look like this:

www.mywebsite.com/en
www.mywebsite.com/de

I’ve tried this with htaccess:

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

or this:

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

But when I try to enter the pages www.mywebsite.com/en or www.mywebsite.com/de, the content doesn’t change.

I guess I have a mistake in the htaccess code…

Also I want to do the same functionality on other pages, so let’s say this page:

www.mywebsite.com/posts?lang=en

to become

www.mywebsite.com/en/posts

2

Answers


  1. To convert http://example.com/file.php?lang=foo to http://example.com/foo/file you can use the following rules in root/.htaccesso :

    RewriteEngine on
    
    #1)remove .php exten#
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^.]+)$ $1.php [NC,L]
    #2)Redirect "/file.php?lang=foo" to "/foo/file"#
    RewriteCond %{THE_REQUEST} /([^.]+).php?lang=([^s&]+)sHTTP [NC]
    RewriteRule ^ /%2/%1? [L,R]
    #3)The rule bellow will internally map "/foo/file" to "/file.php?lang=foo"#
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(en|de)/([^/]+)/?$ /$2.php?id=$1 [L]
    

    [Tested]

    Login or Signup to reply.
  2. You are missing the .php in your new rewrite rules.
    It should be as follows:

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

    As for the problem mentioned in comments (with CSS and JS files), you’ve found the correct solution to that, using:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    This tells apache to not apply the RewriteRule if the request is directed to a real existing file or a directory.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search