Configure conditional forwarding in htaccess

I was asked to create an existing website with several languages.

In preparation for this, I had to migrate all existing pages from / path / page to / en / path / page

To support any existing inbound links, I now need to set up htaccess redirection to send any requests from their source URLs to the new URLs / en / path / page, but I had problems getting this to work.

This is what I have now;

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

I think it is intended to check the requested URI, and if it does not start with / en, then preend / en to the requested URI ... but I am obviously mistaken, since it does not work.

Any help appreciated. Thanks.

UPDATE Since this is an ExpressionEngine site and there is an additional rule for deleting part of the index.php 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 also tried this with rewriting the language after index.php one. I'm still looping on the loops.

+4
source share
1 answer

What it does is checking if the URI is not exactly /en , since $ indicates the end of the line immediately after en .

Try this, it checks if the URI is not exactly /en or /en/ , or does not start with /en/ , and if in this case it adds /en/ :

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

update . Given the other rules that you have in your .htaccess file, it is imperative that the language rule does not match again for the next internal redirect to /index.php... otherwise you end up with an infinite loop.

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

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

Thus, this will result in the rule not being applied after internal redirection. But be careful, this solves the problem for this particular case in which the internal redirect goes to index.php !

+6
source

Source: https://habr.com/ru/post/1497001/


All Articles