Fifi
Fifi

Reputation: 21

.htaccess Redirect Error

I'm trying to redirect http://www.example.co.uk and http://example.co.uk to https://example.co.uk.

In the .htaccess file I have:

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

This redirects the one starting with www. but how I redirect the other as well without the "too many redirects" error occuring?

Upvotes: 1

Views: 106

Answers (1)

arkascha
arkascha

Reputation: 42984

Best is to use two separate rules:

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteRule ^ https://mysite.co.uk%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://mysite.co.uk%{REQUEST_URI} [L,R=301]

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Upvotes: 1

Related Questions