Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up of conditional redirect in htaccess

I've been asked to make an existing web site multi-language.

In preparation for this I have had to move all existing pages from /path/page to /en/path/page

To maintain any existing incoming links I now need to set up an htaccess redirect to send any requests from their original urls to the new /en/path/page urls but I'm having trouble getting this to work.

This is what I currently have;

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

Which I think is meant to check the requested URI and if it doesn't begin with /en then prepend /en onto the requested URI... but I'm obviously mistaken since it doesn't work.

Any help appreciated. Thank you.

UPDATE. Since this is an ExpressionEngine site and there is an additional rule to remove the index.php portion of the URL here are both rules

# Rewrite for new language based urls
# This is to try and get all current pages going to /en/(old url) with a 301 redirect
RewriteCond %{REQUEST_URI} !^/en(/.*)?$
RewriteRule ^(.*)$ /en/$1 [R=301,L]


# Removes index.php
RewriteCond $1 !\.(gif|jpe?g|png|ico)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

I have also tried this with the language rewrite after the index.php one. I'm still getting stuck in loops.

like image 922
foamcow Avatar asked Aug 14 '13 10:08

foamcow


1 Answers

What it does is, checking whether the URI is not exactly /en, since the $ indicates the end of the string right after en.

Try this, it checks whether the URI is not exactly /en or /en/ or doesn't start with /en/, and if that's the case it will prepend /en/:

RewriteCond %{REQUEST_URI} !^/en(/.*)?$
RewriteRule ^(.*)$ /en/$1 [R=301,L]

update Considering the other rules you have in your .htaccess file, it is necessary to have the language rule not match again for the following internal redirect to /index.php..., otherwise you'll end up with an endless loop.

There may be better ways to prevent this, however the first thing that comes to my mind would be checking for index.php in the first condition:

RewriteCond %{REQUEST_URI} !^/(index\.php|en)(/.*)?$

So this will cause the rule not to apply after the internal redirect. But be careful, this solves the problem for this specific case only in which the internal redirect goes to index.php!

like image 106
ndm Avatar answered Oct 14 '22 04:10

ndm