Send visitors to the HTTPS address
Visitors who open a page over plain http are redirected to the same page on https. Only runs on the live site (production), so local copies keep working.
Before you switch it on: Open your site at https:// first. Behind Cloudflare’s Flexible SSL or a proxy that doesn’t tell WordPress about HTTPS, this would redirect in a loop: don’t use it there.
It arrives switched off, even when you install its whole pack with "Switch on after installing".
<?php
add_action(
'template_redirect',
static function () {
if ( is_ssl() || 'production' !== wp_get_environment_type() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
$host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
$uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '/';
if ( $host && wp_parse_url( home_url(), PHP_URL_HOST ) === $host ) {
wp_safe_redirect( 'https://' . $host . $uri, 301 );
exit;
}
},
1
);
Good to know
Set your WordPress and site addresses to https:// too (Settings > General). If your host already redirects to https, you don’t need this.
In these packs
- Login and security extras: Limit login attempts, email-only logins, a registration spam trap and more hardening.