Home > front end >  Adding directory to url with htaccess & rewrite
Adding directory to url with htaccess & rewrite

Time:11-15

I have a site based on Modx CMS and I need to create a 301 redirect for the main folder & old links after the multilanguage functionality has been enabled.

What I need to achieve is the default fallback to english eg. make sure that:

example.com/products -> example.com/en/products example.com/about - example.com/en/about etc.

I also need to make sure that if there already is a language selection (for example de) in the url, I don't add en to url. (so no example.com/en/de/products)

I am having trouble adding the /en/ to url and I am ending up with infite /en/en/en loops on the URL

To add the /en/ to the url I tried the following.

RewriteCond %{REQUEST_URI} !^/de$
RewriteCond %{HTTP_HOST} .*example.com [NC]
RewriteRule ^https://example.com/en/%{REQUEST_URI} [L,R=301]

It results to a endless /en/en/en loop in the url.

The whole htaccess is as follow:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteBase /

RewriteCond %{REQUEST_URI} !^/de$
RewriteCond %{HTTP_HOST} .*example.com [NC]
RewriteRule ^https://example.com/en/%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

CodePudding user response:

Try the code below. The rules are chained (the default is AND). So, if your URL doesn't start with /en, /de, it's not the index (/), and it's not a file name or a directory, do a 301 redirect to the English version:

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/en
RewriteCond %{REQUEST_URI} !^/de
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ https://%{HTTP_HOST}/en%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
  • Related