John Svensson
John Svensson

Reputation: 461

Apache 301 Redirect Add language prefix if not present

RewriteEngine on
RewriteCond %{HTTP_HOST} ^test\.hemsida\.eu$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.hemsida\.eu$
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ "https\:\/\/testar\.se\/sv/$1" [R=301,L]

So this one will redirect all traffic from test.hemsida.eu to https://testar.se/sv/$1

But the problem is if test.hemsida.eu contains sv in the path, it redirects: https://testar.se/sv/sv/test

How can I get rid of one the sv, but still maintain it, if it isn't present in the URL?

Upvotes: 1

Views: 294

Answers (1)

anubhava
anubhava

Reputation: 785128

You can use it like this by tweaking your regex:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^(?:www\.)?test\.hemsida\.eu$ [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ [NC]
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ [NC]
RewriteRule ^(?:sv/)?(.*)$ https://testar.se/sv/$1 [NC,NE,R=301,L]

(?:sv/)? (optional match) at the start of pattern will make sure that you always capture whatever comes after /sv/ or if there no /sv/ then complete match.

Upvotes: 1

Related Questions