Rewrite Rule to enforce default lang code in URL

2019-05-25 00:39发布

问题:

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

1 . Example URL without qtranslate:

www.mysite.com/post1

2 . Example URL with localized content:

www.mysite.com/en/post1 (english - my default and fallback)

www.mysite.com/de/post1

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!

回答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:

What about just using meta canonical?

Like this:

<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish" />

More info: http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html



回答3:

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]