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

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: https, ssl, security
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/force-https-redirect/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Force HTTPS on the Front End" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
