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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.