# Redirect Missing Resized Images to the Original

> Sends requests for resized images that no longer exist, such as photo-300x200.jpg after a theme change, to the original upload, fixing broken images in old posts and on other sites.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: redirects, images, uploads
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/missing-image-sizes-to-original/

## 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 ) ) : '';
    $uploads = wp_get_upload_dir();
    $base    = (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH );

    // Only resized copies such as photo-300x200.jpg inside the uploads folder.
    if ( '' === $path || 0 !== strpos( $path, trailingslashit( $base ) ) || ! preg_match( '/^(.+)-\d+x\d+(\.(?:jpe?g|png|gif|webp|avif))$/i', $path, $m ) ) {
        return;
    }

    $relative = substr( $m[1], strlen( $base ) );

    if ( false !== strpos( $relative, '..' ) ) {
        return;
    }

    // Large uploads keep their original as name-scaled.jpg; check that first.
    foreach ( array( '-scaled', '' ) as $suffix ) {
        $file = $relative . $suffix . $m[2];

        if ( file_exists( $uploads['basedir'] . $file ) ) {
            wp_safe_redirect( $uploads['baseurl'] . implode( '/', array_map( 'rawurlencode', explode( '/', $file ) ) ), 301 );
            exit;
        }
    }
} );
```

## Notes

Only works when your web server passes missing upload files to WordPress, as the default Apache setup does.

## How to use it

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