sub_lunar sub_lunar - 1 year ago 85
Apache Configuration Question

htaccess force https and redirect www to non-www, but no other subdomains

I know there are many similar threads, but none of them seems to match my exact problem. Here is what I’m trying to do:

(1) ->
(2) ->
(3) ->

Ideally, I would also like to cover the situation if I will ever add more subdomains, to automatically behave like the following (preferably in a generic way that will work for any subdomain I add).

(4) ->

At this point I’m wondering if it is even possible to create a single .htaccess file that does everything I need, although I have to admit that I understand regexes, but I’m not exactly a mod_rewrite uberpro.

Here are the solutions that I already tried:

My SSL certificate covers the www-subdomain, so I’m not looking for a 'untrusted connection' error solution, I’m aware that isn’t possible.

Answer Source

Put this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{ENV:HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301,NE]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download