3

I need to set up a redirect from the www version of my site to the non-www version for SEO. I found a solution that would work here if it weren't for the fact that it breaks the index.php redirect that comes with craft.

Can anyone tell me how to implement a generic redirect from http://www.site.co.uk to http://site.co.uk and still keep the index.php craft redirect working?

Additionally, does this affect the config.php file, or does that get loaded AFTER the redirect?

Thanks!

4

Providing you have the necessary permissions to do this, the following in your .htaccess should do the job:

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

In place, the full file will probably look something like this:

<IfModule mod_rewrite.c>
RewriteEngine On

# Redirect to non-www domain
RewriteCond %{HTTP_HOST} !^domain\.co\.uk$ [NC]
RewriteRule ^(.*)$ http://domain.co.uk/$1 [R=301,L]

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

The following seems to work for me as a generic option:

<IfModule mod_rewrite.c>
RewriteEngine On

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

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

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>
  • That seems to work, thanks Steve. Any idea how I might do it generically without using the domain name? – darylknight Jan 8 '15 at 15:03
  • I've updated the above with some generic code (taken from your original post) that seems to work for me without error. Can you give it a shot and see? – Steve Abraham Jan 8 '15 at 15:19
  • Seems to be fine, thanks muchly! codeknight.co.uk/portfolio – darylknight Jan 8 '15 at 16:15
  • If you are using .htaccess for the redirect, the redirect happens before index.php is called (and therefore also before config.php is called.) – Marion Newlevant Jan 8 '15 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.