Search code examples
apache.htaccesshttp-redirecthttp-status-code-404

htaccess redirect missing bundle.*.js version to bundle.js file


I am using htaccess redirect to send missing assets to Apache 404 for optimization.

# BEGIN Apache 404 for broken resouces
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(jpg|jpeg|png|gif|ico|icns|swf|bmp|css|js)$ - [nocase,redirect=404,last]
# END Apache 404 for broken resouces

Although this should also serve the last file if file is missing I'd like to update this with the following to avoid caching issues:

- if bundle.[version].js or bundle.[version].css is missing serve bundle.js or bundle.css instead. Currently unable to achieve this. Any ideas to improve this?


Solution

  • serve bundle.js or bundle.css instead.

    Just to note, in your comment, you wrote this as build.js and build.css respectively?

    You could either, create another .htaccess file in the /wp-content/themes/custom-theme/build subdirectory (which contains both the .js and .css files) with the following directives:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^bundle\.\w+\.(js|css)$ bundle.$1 [L]
    

    OR, add the following directives to the top of the root .htaccess before your existing directives:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)/bundle\.\w+\.(js|css)$ $1/bundle.$2 [L]
    

    The first option is marginally more efficient as it completely overrides the directives in the parent .htaccess file and is only processed on the necessary requests. However, the second option is perhaps easier to maintain as it keeps all your directives in one place.