25% off ProSNIPC25OFF

Force HTTPS Redirect Site-Wide

Permanently redirects all non-HTTPS requests to their secure equivalent and adds an HSTS header.

PHPby SnipCraft
php
<?php
add_action( 'template_redirect', 'scseed_force_https', 1 );
function scseed_force_https() {
    if ( is_ssl() ) {
        return;
    }
    // Build the HTTPS URL and issue a 301 permanent redirect.
    $host = sanitize_text_field( $_SERVER['HTTP_HOST'] ?? '' );
    $uri  = sanitize_url( $_SERVER['REQUEST_URI'] ?? '/' );
    wp_redirect( 'https://' . $host . $uri, 301 );
    exit;
}

// Add Strict-Transport-Security so browsers enforce HTTPS themselves.
add_action( 'send_headers', 'scseed_add_hsts_header' );
function scseed_add_hsts_header() {
    if ( is_ssl() ) {
        header( 'Strict-Transport-Security: max-age=31536000; includeSubDomains' );
    }
}
#https#redirect#security#ssl