Frederik Junkuhn
Frederik Junkuhn

Reputation: 25

301 redirect non-www in subfolder via .htaccess

I'm trying to redirect all non-www pages to a www page on my site using the .htaccess file. It's a multilingual site and it's set up with a site in the root folder in danish, and an English version in www.domain.com/en/.

I got the non-www redirect working on the danish part but I'm having problems in the english subfolder. Each folder has it's own .htaccess.

On the danish end my request looks like this:

#301 redirect #RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*) http://www.example.com/$1 [R=301] 

And I'm thinking that the English equivalent should look like this:

#RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com/en/$
RewriteRule ^(.*) http://www.example.com/en/$1 [R=301] 

I would really appreciate any help I can get.

Upvotes: 1

Views: 1266

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

You can't include the path as part of the %{HTTP_HOST} variable, which only contains the hostname. Thus, RewriteCond %{HTTP_HOST} ^example\.com/en/$ will always be false.

You can match the path as part of the regex in the rewrite rule:

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^en/(.*)$ http://www.example.com/en/$1 [R=301] 

But this doesn't make any sense. If you're placing these rules in the /en/ folder, then you don't need to check for the /en/ at all:

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://www.example.com/en/$1 [R=301] 

Since the rules won't get processed if you aren't already requesting something that starts with /en/

Upvotes: 0

Related Questions