SSL and dropping “www.” with mod_rewrite

Michał ‘mina86’ Nazarewicz | 10 lutego 2013

Surprisingly I couldn’t find any HTTPS-aware examples how to drop the www. prefix from web hosts in Apache, so I had to come up with one myself. Firstly, the following lines need to find their way to the end of Apache configuration file (/etc/httpd/conf/httpd.conf or something):

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

Secondly, analogous lines need to be added inside of the <VirtualHost _default_:443> directive of mod_ssl configuration file (/etc/httpd/conf.d/ssl.conf or similar), like so:

<VirtualHost _default_:443>
	# … various directives …

	# Here’s what needs to be added:
	RewriteEngine on
	RewriteCond %{HTTP_HOST} ^www\.(.*)$
	RewriteRule ^(.*)$ https://%1$1 [L,R=301]
</VirtualHost>

Now, after a restart, Apache will drop the www. prefix for both secure and insecure connections.

To force secure connection and drop the prefix at the same time the part in main configuration file has to become:

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

To force secure connection only for one domain, say example.com:

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?(example\.com)$
RewriteRule ^(.*)$ https://%2$1 [L,R=301]

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

mod_rewrite has also a REQUEST_SCHEME variable and it’s tempting to use it, but it seems that it’s value is not what is advertised and instead it contains scheme and host name which is not that useful.

If you want to add the prefix, check out this site.