简体   繁体   中英

htaccess language conditional redirect

I need to make a redirect in my htaccess, depending on the presence or not of the language code in the url.

Url structure should start with the domain followed by the language code and then, the specific page (as any regular site)

domain.com/ en /section/subsection/

As you can see, the /en/ is the language code, but there could be different language codes [/en/es/it/]

So rules should be as follows:

  • language code must be present and it must be 2 characters long

if this rule is not matched, browser should be redirected to the default lang "/en/"

In my mind it is something like this... only in my mind ;)

RewriteCond %{REQUEST_URI} !^/([az]){2}/(.*)$
RewriteRule ^(.*)$ /en/$1 [L]

Thanks in advance

Your regex doesn't seem right and you can do this in RewriteRule itself:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^[a-z]{2}/ /en%{REQUEST_URI} [R=301,L]

With the help of @anubhava, finally this code worked like a charm. Thanks!!

RewriteCond %{REQUEST_URI} !^(.+)\.(js|css|png|jpe?g|gif|eot|woff2?|ttf|otf|svg|json|txt|xml|html?|htc|ico|m4a|m4v|manifest|mp4|mp3|oex|oga|ogg|ogv|otf|pdf|swf|fla|safariextz|svgz?|vcf|webapp|webm|webp|xpi)$ [NC]
RewriteRule !^[a-z]{2}/ /en%{REQUEST_URI} [R=301,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM