# Redirect to the www or Non-www Version of Your Domain

> Sends visitors who arrive on the other version of your domain (with or without www) to the one set as your Site Address, so search engines see a single site.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: www, domain, canonical
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/www-host-consistency/

## Code

```php
add_action( 'template_redirect', function () {
    $home_host = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
    $request   = isset( $_SERVER['HTTP_HOST'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) ) : '';
    $request   = preg_replace( '/:\d+$/', '', $request );

    if ( '' === $request || $request === $home_host ) {
        return;
    }

    $bare_home    = preg_replace( '/^www\./', '', $home_host );
    $bare_request = preg_replace( '/^www\./', '', $request );

    if ( $bare_home !== $bare_request ) {
        return;
    }

    $scheme = wp_parse_url( home_url(), PHP_URL_SCHEME );
    $uri    = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';

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

## Notes

Your host must point both versions to this site. A redirect at the server or DNS level is faster when available.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect to the www or Non-www Version of Your Domain" 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/
