# Redirect All Traffic to HTTPS

> Permanently redirects every plain HTTP request to the HTTPS version of the same URL, for sites whose host does not do it already.

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

## Code

```php
add_action( 'init', function () {
    if ( is_ssl() || ( defined( 'WP_CLI' ) && WP_CLI ) || wp_doing_cron() || empty( $_SERVER['HTTP_HOST'] ) ) {
        return;
    }

    // Many proxies and load balancers terminate HTTPS and pass this header instead.
    if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && 'https' === strtolower( (string) $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
        return;
    }

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

    wp_safe_redirect( 'https://' . $host . $uri, 301 );
    exit;
}, 0 );
```

## Notes

Make sure your SSL certificate works first, and set both site URLs in Settings > General to https://.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect All Traffic to HTTPS" 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/
