Forcing New Sites to HTTPS in a WordPress Multisite Subdomain Network

I had an old coworker reach out today about the multisite network I used to work on at UNC. It’s set up as a subdomain installation and new sites that were being created were not automatically being set to HTTPS and he wanted to know how to change that.

Background Information

If you use a subdirectory multisite network, any new subsites will follow the scheme from the primary site of the network. But on a subdomain network, this is hardcoded to force all new sites to be HTTP.

It’s been proposed to change it mimic subdirectory networks and use the same scheme as the primary site, but the thinking is that you can’t ensure that a user will have a certificate for the new domain, making the new site unreachable.

The Fix

If you’ve got a wildcard certificate in place for the domain of the primary site of the network, then your subdomains will work just fine on HTTPS, so it would be ideal to be able to force this setting when creating new sites in that situation.

There isn’t a clearly identifiable filter specific to scheme or new site URLS, but it can be accomplished using the wp_initialize_site_args filter.

<?php
add_filter( 'wp_initialize_site_args', function( $args, $site ) {
	$url = untrailingslashit( 'https://' . $site->domain . $site->path );

	$args['options']['home']    = $url;
	$args['options']['siteurl'] = $url;

	return $args;
}, 10, 2 );Code language: PHP (php)

Put the above snippet in an file in the mu-plugins directory and it should take care of it for all new sites created either by users on the front-end, or network administrators in the admin.

HTTPS Going Forward

Hopefully we can do some work around that in the future to detect the availability of HTTPS and default to using it if possible.

There are some new efforts underway to encourage site owners to use HTTPS and help them reach out to their hosting providers to enable it if it’s not available.

5 Comments

  1. Thanks for the solution! Just, what I needed.

    I also add a fix for your code: the untrailingslashit is missing at the $url. This is, how WP is doing also in /wp-includes/ms-site.php file at 747-748 lines.

    `$url = untrailingslashit( ‘https://’ . $site->domain . $site->path );`

    • Good callout. Updated the post to add that. I think it would be ok, but could probably lead to some unexpected behavior since WP doesn’t put trailing slashes on home and siteurl by default.

Comments are closed.