0

I tried to write a rule for multilingual site. For example, www.hostname.com/fr & www.hostname.com/de are ok, but trying any other language tag should redirect to www.hostname.com/en. www.hostname.com/it redirects to www.hostname.com/en, www.hostname.com/es redirects to www.hostname.com/en etc...

I succeed to make some rules in a "positive" way, but each time I add a ! to create a negative rule, it doesn't work.

For example :

RewriteCond %{HTTP_HOST} ^www.hostname.com$
RewriteCond %{REQUEST_URI} ^/?([a-z]{2})/?$
RewriteCond %{REQUEST_URI} ^/?(fr|de)/?$
RewriteRule (.*) http://www.hostname.com/en [L,R=301]

This code redirects everything to hostname.com/en. I want that only tag different than fr et de redirect to en. So I tried :

RewriteCond %{HTTP_HOST} ^www.hostname.com$
RewriteCond %{REQUEST_URI} ^/?([a-z]{2})/?$
RewriteCond %{REQUEST_URI} !^/?(fr|de)/?$
RewriteRule (.*) http://www.hostname.com/en [L,R=301]

Just added a !. But it doesn't work, URL are never redirected. I've probably missed something in writing rules...

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
Neow
  • 11
  • 3
  • 1
    Your negative rule works exactly as expected when I test at http://htaccess.madewithlove.be. However, you will have a rewrite loop on the `en`. You probably need `!^/?(fr|de|en)/?$` Also, the REQUEST_URI should always begin with `/` so the `?` to make it optional isn't necessary. – Michael Berkowski Apr 08 '13 at 16:16
  • I agree with Michael Berkowski. You're suffering an infinite loop because the /en path is being redirected to itself. The `L` flag in mod_rewrite does not behave as a lot of people think. Even a rewritten URL has to go through the httpd.conf or .htaccess directives from the top, and the `L` flag does not stop this happening. – Bobulous Apr 08 '13 at 18:48

1 Answers1

1

You can split this into two rules. The first rule handles fr, de and en. It doesn't rewrite anything and passes the request unchanged to Apache. If this doesn't match, the second rule handles everything else

RewriteCond %{REQUEST_URI} ^/(?:fr|de|en)
RewriteRule ^ - [L]

RewriteRule ^[a-z]{2}/(.*)$ /en/$1 [R,L]

Never test with 301 enabled, see this answer Tips for debugging .htaccess rewrite rules for details.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198