# Redirect Old .html Page Addresses

> Sends visitors from addresses of a previous static site, such as /about.html or /services/web.php, to the WordPress page with the same name.

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

## Code

```php
add_action( 'template_redirect', function () {
    if ( ! is_404() ) {
        return;
    }

    $path = isset( $_SERVER['REQUEST_URI'] ) ? rawurldecode( (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) ) : '';

    if ( ! preg_match( '#^/?(.*?)([^/]+)\.(?:html?|php|aspx?)$#i', $path, $match ) ) {
        return;
    }

    if ( 'index' === strtolower( $match[2] ) && '' === trim( $match[1], '/' ) ) {
        wp_safe_redirect( home_url( '/' ), 301 );
        exit;
    }

    $post = get_page_by_path( trim( $match[1] . $match[2], '/' ), OBJECT, array( 'page', 'post' ) );

    if ( ! $post ) {
        $post = get_page_by_path( sanitize_title( $match[2] ), OBJECT, array( 'page', 'post' ) );
    }

    if ( $post && 'publish' === $post->post_status ) {
        wp_safe_redirect( get_permalink( $post ), 301 );
        exit;
    }
} );
```

## Notes

Only runs when the old address would otherwise be a 404. /index.html goes to the homepage.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect Old .html Page Addresses" 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/
