John Svensson John Svensson - 9 days ago 10
Apache Configuration Question

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?

Answer

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.