Fast 404 for Missing Images, Scripts and Styles
Answers requests for missing images, CSS, JavaScript and font files with a tiny 404 instead of loading a full theme page, saving server time.
Opens WPIDE on
Code
// File extensions that should never be handled by WordPress pages.
$wpide_static_extensions = array( 'jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'css', 'js', 'map', 'woff', 'woff2', 'ttf', 'eot', 'otf', 'mp4', 'webm', 'mp3' );
if ( ! is_admin() && ! ( defined( 'WP_CLI' ) && WP_CLI ) && isset( $_SERVER['REQUEST_URI'] ) ) {
$wpide_path = (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH );
$wpide_ext = strtolower( pathinfo( $wpide_path, PATHINFO_EXTENSION ) );
if ( $wpide_ext && in_array( $wpide_ext, $wpide_static_extensions, true ) ) {
status_header( 404 );
nocache_headers();
header( 'Content-Type: text/plain; charset=utf-8' );
exit( 'Not found' );
}
}
Notes
Do not use it with plugins that create image sizes on the fly when a file is missing.
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.