Search code examples
wordpressapache.htaccesssslmod-rewrite

.htaccess rule to force SSL on only certain domains


I'm running a WordPress multisite network that allows users to optionally use a custom domain name on their websites. Users that opt not to use a custom domain are assigned a subdomain of the WP install (e.g.: fred.example.com, with example.com being the URL the WP multisite network is installed on).

I have a wildcard SSL configured for the main domain, but I do not have certificates available for custom domain names.

What I need is a htaccess rule to force traffic to https if the request is for either example.com or *.example.com, but not if the request is coming in using a custom domain.

It should work as follows:

  • http://example.com/*https://example.com/*
  • http://foo.example.com/*https://foo.example.com/*
  • http://customdomain.com/*http://customdomain.com/*

Solution

  • Try something like the following near the top of your .htaccess file. Using mod_rewrite:

    RewriteEngine On
    RewriteCond %{HTTPS} !on
    RewriteCond %{HTTP_HOST} ^(?:[a-z0-9-]+\.)?example\.com
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]
    

    What this says is... For all requests that are not HTTPS and that match example.com or <subdomain>.example.com then redirect to https:// on the same host, same URL-path.

    Note that this doesn't allow www.<subdomain>.example.com (which I assume your SSL cert does not cover anyway).

    Change the 302 (temporary) to 301 (permanent) only when you are sure it's working OK.