deacs
deacs

Reputation: 4309

.htaccess force 'www.' and append the rest of url to the end as normal

Right, I have a .htaccess file that looks like this:

RewriteEngine On
RewriteRule ^foto/([\w-]+).jpg fotos.php?pic1=$1 [L,NS]
RewriteRule ^afbeeldingen/([\w-]+).jpg fotos.php?pic=$1 [L,NS]
RewriteRule ^header/([\w-]+).jpg header.php?head_jpg=$1 [L,NS] 
RewriteRule ^header/([\w-]+).png header.php?head_png=$1 [L,NS] 
RewriteRule ^def/([\w-]+).jpg def_header.php?head_def=$1 [L,NS] 

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php 
RewriteRule . index.php

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

The question concerns only the last 2 lines, namely I want to force 'www.' in front of all urls. This is the result that I want when trying to access the sitemap.xml:

http://domain.com/sitemap.xml -> http://www.domain.com/sitemap.xml

This is the result I am getting:

http://domain.com/sitemap.xml -> http://www.domain.com/index.php

All other url's seem to be working fine (thanks to anubhava). The 'www.' is forced properly on url's such as http://domain.com/category/article -> http://www.domain.com/category/article

After reading the following stack question (.htaccess force "www." on everything but subdomains and remove trailing slashes) I have tried the following:

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

without any succes. I have also tried changing the order in which the rules are put (i.e. the rewrite condition and rule underneath RewriteEngine On) which doesn't seem to make a difference. I'm using the Yii Framework.

Anybody have any idea what I'm doing wrong here? Thanks in advance!

UPDATE

I forgot to mention that I do NOT actually have a sitemap.xml file in the root, rather I am using Yii's urlManager to reroute to a controller action to generate the sitemap.xml like so:

'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName'=>false,
    // 'matchValue' => true,
    'rules'=>array( 
        ...
        'sitemap.xml'=>'site/sitemapxml',
        ...
    ),
),

The urlManager generates a .htaccess file itself, which is most likely buggering with my own .htaccess file. Any idea's?

Upvotes: 2

Views: 256

Answers (2)

Lionel
Lionel

Reputation: 2029

How about this:

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

Upvotes: 1

anubhava
anubhava

Reputation: 785246

Order of rules matter in .htaccess.

Move this rule:

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Just below RewriteEngine On line.

Upvotes: 4

Related Questions