Home > Mobile >  enable caching of images only in specific folder
enable caching of images only in specific folder

Time:09-03

I have the below htacess code and am wondering how i can specify it to only apply to a specific folder. in this case, only all image files in: /public_html/img/icons/

<filesMatch ".(png)$">
    Header set Cache-Control "max-age=31536000, public"
</filesMatch>

CodePudding user response:

Set an environment variable (using SetEnvIf) when the URL requested matches the specific folder and image type(s). Set the Header conditionally based on this env var (using the env= argument of the Header directive).

For example:

# Cache images in the "/img/icons" subdirectory
SetEnvIf Request_URI "^/img/icons/. \.(png|jpg|gif)$" ENABLE_CACHE
Header set Cache-Control "max-age=31536000, public" env=ENABLE_CACHE

This method allows you to keep all the directives in the single .htaccess file in the document root. It also works on all versions of Apache (unlike <If> expressions that require Apache 2.4).

However, this may also be dependent on other directives you have in the .htaccess file. If, for instance, you are on Apache (as opposed to LiteSpeed) and rewriting the URL with mod_rewrite (a front-controller pattern perhaps) then you may need to test for REDIRECT_ENABLE_CACHE in the Header directive instead. (Or change your existing directives to prevent a loop of the rewrite engine, that results in the env var being prefixed with REDIRECT_.)

  • Related