WordPress Rewrite Rule to enforce default lang code in URL

I am running a WP Blog with qtranslate. It allows me to create posts in multiple languages.

1 . Example URL without qtranslate:

Read More

2 . Example URL with localized content:

Unfortunately search engines etc. still remember my old links (1.) and these are still access-able. So “www.mysite.com/post1” now shows my english content without a redirect. But what it should do is to 301 users to “www.mysite.com/en/post1”.

So now I would need a rule that basically checks if there is /en/post1 or a /de/post1 in the URL and otherwise redirect to the fallback /en/post1 URL. There is one exception because “/shop” is a real subdirectory and does not need to be preceeded by language information.

— UPDATE —

I did it!!! That was actually fun but took me quite a while to figure out.

RewriteRule ^$ en [R=301,L]
RewriteRule ^([a-z]{2})/{1}$ $1 [R=301,L]
RewriteRule ^([a-zA-Z0-9-_]{3,})(/|$)$ en/$1 [R=301,L]

There are probably better ways to do this but it does the trick. Thanks everyone for the initial help!

Related posts

Leave a Reply

3 comments

  1. Have you tried using a universal RewriteRule, and using RewriteConds to eliminate the cases that you don’t want it to rewrite?

    It would go something like:

    RewriteCond %{REQUEST_URI} !^/shop(/|$)
    RewriteCond %{REQUEST_URI} !^/(en|de)(/|$)
    RewriteRule ^(.*)$ /en/$1 [R=301]
    

    But as per Camilo’s suggestion, you could change that middle line to

    RewriteCond %{REQUEST_URI} !^/[a-z]{2}(/|$)
    

    as long as you can ensure that your post permalinks won’t be less than three characters (I’m not familiar enough with WordPress to be sure if that’s possible).

  2. I did it!!! That was actually fun but took me quite a while to figure out.

    RewriteRule ^$ en [R=301,L]
    RewriteRule ^([a-z]{2})/{1}$ $1 [R=301,L]
    RewriteRule ^([a-zA-Z0-9-_]{3,})(/|$)$ en/$1 [R=301,L]
    

    There are probably better ways to do this but it does the trick

    — UPDATE this includes support for longer URLs —

    RewriteRule ^([a-zA-Z0-9-_]{3,}(/|$).*)$ en/$1 [R=301,L]
    RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]