Galen Gidman
Galen Gidman

Reputation: 552

.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:

Upvotes: 3

Views: 726

Answers (1)

MrWhite
MrWhite

Reputation: 45829

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.

Upvotes: 4

Related Questions