Halloween Sale 15% off Ends in See the plans
PHP

Force HTTPS on the Front End

Sends visitors who open a page over plain HTTP to the secure HTTPS address with a permanent redirect, once your site URL is set to https.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'template_redirect', function () {
    if ( is_ssl() || 'https' !== wp_parse_url( home_url(), PHP_URL_SCHEME ) ) {
        return;
    }

    $forwarded = isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) ) : '';
    $visitor   = isset( $_SERVER['HTTP_CF_VISITOR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_VISITOR'] ) ) : '';

    if ( false !== strpos( $forwarded, 'https' ) || false !== strpos( $visitor, 'https' ) ) {
        return;
    }

    $host    = wp_parse_url( home_url(), PHP_URL_HOST );
    $port    = wp_parse_url( home_url(), PHP_URL_PORT );
    $request = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';

    wp_safe_redirect( 'https://' . $host . ( $port ? ':' . $port : '' ) . $request, 301 );
    exit;
}, 0 );

Notes

Only runs when the Site Address already starts with https. Proxies and CDNs that report HTTPS through standard headers are detected, so it does not loop behind Cloudflare or a load balancer.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.