Add expires header for all files except specific files - .htaccess

I'm trying to add expires headers to all files except some specific files. In fact, I'm using a caching tool, that adds the following code to my htaccess:
# BEGIN LBCWpFastestCache
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|webp|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)(\.gz)?$">
<IfModule mod_expires.c>
AddType application/font-woff2 .woff2
ExpiresActive On
ExpiresDefault A0
ExpiresByType image/webp A2592000
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/ico A2592000
ExpiresByType image/svg+xml A2592000
ExpiresByType text/css A2592000
ExpiresByType text/javascript A2592000
ExpiresByType application/javascript A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType application/font-woff2 A2592000
</IfModule>
<IfModule mod_headers.c>
Header set Expires "max-age=2592000, public"
Header unset ETag
Header set Connection keep-alive
FileETag None
</IfModule>
</FilesMatch>
# END LBCWpFastestCache
I want to make an exception for two different images on my page. Let their names be file-a and file-b, here is what I tried:
I put this code after the code from the plugin.
<FilesMatch "\.(file-a|file-b)$">
ExpiresDefault "access plus 1 hour"
</FilesMatch>
Since that didn't work, I also tried putting it before the code, which didn't work either.
Then I tried manipulating the FilesMatch part of the code added by the plugin, so that it excludes my files.
<FilesMatch "(?!.*/(file-a|file-b))(\.(ico|pdf|flv|jpg|jpeg|png|gif|webp|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)(\.gz)?$)">
Didn't work either.
How do I achieve this?

It is not enough to assert the banned files names since the following capture group can sill match the allowed file extensions. You should be able to solve it using a tempered greedy token:
^((?!\/file-a|file-b).)*(\.(ico|pdf|flv|jpg|jpeg|png|gif|webp|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)(\.gz)?$)
Demo

You can use a negative lookbehind regex search.
Check out this regex101 playground
<FilesMatch "(?<!file-a|file-b)(\.(ico|pdf|flv|jpg|jpeg|png|gif|webp|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)(\.gz)?$)">

Related

How to leverage browser caching for static HTML assets?

I have built my static html on heroku. Here's the link: https://askheating.herokuapp.com/
Now when I am performing a test on GTMetrix, I have got a very bad score due to leverage browser caching.
This is my .htaccess script
AddType application/vnd.ms-fontobject .eot
AddType application/x-font-ttf .ttf
AddType application/x-font-opentype .otf
AddType application/x-font-woff .woff
AddType image/svg+xml .svg
# BEGIN Expire headers
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 5 seconds"
ExpiresByType image/x-icon "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
ExpiresByType text/html "access plus 600 seconds"
ExpiresByType application/xhtml+xml "access plus 600 seconds"
</ifModule>
# END Expire headers
# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
<filesMatch "\.(ico|jpe?g|png|gif|swf)$">
Header set Cache-Control "public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "private"
</filesMatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "private, must-revalidate"
</filesMatch>
</ifModule>
# END Cache-Control Headers
# This is for gzip, which compresses files
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
#Remove the Need for www in Your URL
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.askheating.herokuapp.com [NC]
RewriteRule ^(.*)$ https://askheating.herokuapp.com/$1 [L,R=301]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# disable directory browsing
Options All -Indexes
But still I'm getting this
Now I dont know how to play with nginx, and whwre to find all that stuff..
please help!!
Browser caching for .htaccess
The code below tells browsers what to cache and how long to "remember" it. It should be added to the top of your .htaccess file.
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
Save the .htaccess file and then refresh your webpage.
How to set different caching times for different file types
You can see in the above code that there are time periods like "1 year" or "1 month". These are associated with file types, as an example the above code states that a .jpg file (image) should be cached for a year.
If you want to change that and say you want your jpg images cached for a month you would simply replace "1 year" with "1 month". The values above are pretty optimized for most webpages and blogs.
Alternate caching method for .htaccess
The above method is called "Expires" and it works for most people using .htaccess so it takes care of caching for most people who are just getting started.
After you are more comfortable with caching, you may want to try Cache-Control, another method of caching which gives us more options.
It is also possible the expires method did not work for your server, in that case you may want to try to use Cache-Control.
Cache-Control
Cache-Control allows us to have a bit more control of our browser caching and many people find it easier to use once setup.
Example use in .htaccess file:
# 1 Month for most static assets
<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
The above code is setting a cache control header depending on file type.
https://varvy.com/pagespeed/leverage-browser-caching.html
https://medium.com/#codebyamir/a-web-developers-guide-to-browser-caching-cc41f3b73e7c

Upload new files when .htaccess cach is set to one week?

I need to upload a new version of a CSS-file, but nothing happens. Then I discovered that the cach of CSS files was set to one week in the .htaccess file one the Apache server like this:
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 week"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 week"
ExpiresByType text/html "access 1 week"
ExpiresByType text/x-javascript "access 1 week"
ExpiresDefault "access 1 week"
</IfModule>
## EXPIRES CACHING ##
Is there a way to override this, so that the new CSS file can be used? I have tried to just remove this lines, but the old CSS files is still active on the site.
For Disabling cache you can use this piece of code in your htaccess file
# DISABLE CACHING
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
You will have more information over this link

Leverage browser caching not working using htaccess

I am trying to add browser caching in my .htaccess to boost my google page speed score (currently at 86) however its not working. I have used 2 different types and both keep failing the google page speed results.
It was working on our old site (build on laravel php) however just not the new one which is just HTML/CSS/JS
I have used the following:
<filesMatch ".(css|jpg|png|svg|ico|js|php)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
and also
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType text/html "access 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access 1 month"
ExpiresByType text/plain "access 1 month"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType application/pdf "access 1 year"
ExpiresByType application/x-shockwave-flash "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##
and both keep failing. I have placed it at the very top.
I have looked at other responses from here before posting this and still couldn't get it to work. Any help will be greatly appreciated
Thanks
David
Try this syntax:
ExpiresByType image/* A31536000
And try adding backslashes and a question mark:
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|svg|swf|mp3|vtt|)(\.gz)?$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
Ok thanks for the reply
Will give it a go tomorrow when at work and will update - thanks again

Add Expires headers on Yslow doesn't have any effect

I have mod_expires and mod_headers enabled on the server and this code in htaccess:
<FilesMatch "\.(htm|html|xhtml|css|js|php)$">
AddDefaultCharset UTF-8
Header set Content-Language "en-US"
</FilesMatch>
<IfModule mod_headers.c>
Header set Vary "Accept-Encoding"
</IfModule>
php_value session.cookie_domain "www.domain.com"
Options -Indexes
# year
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$">
Header set Cache-Control "public"
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
Header unset Last-Modified
</FilesMatch>
#2 hours
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</FilesMatch>
<FilesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"
</FilesMatch>
<FilesMatch ".(eot|ttf|otf|woff)">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*.domain.com"
</IfModule>
</FilesMatch>
<IfModule mod_deflate.c>
# Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines as
# `AddOutputFilterByType` is still in the core directives)
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
Options +FollowSymlinks
RewriteEngine On
<ifModule mod_headers.c>
Header unset ETag
</ifModule>
FileETag None
<IfModule mod_expires.c>
ExpiresActive on
# Perhaps better to whitelist expires rules? Perhaps.
ExpiresDefault "access plus 1 month"
# cache.appcache needs re-requests in FF 3.6 (thx Remy ~Introducing HTML5)
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Data
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"
# Favicon (cannot be renamed)
ExpiresByType image/x-icon "access plus 1 month"
# Media: images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# HTC files (css3pie)
ExpiresByType text/x-component "access plus 1 month"
# Webfonts
ExpiresByType font/truetype "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
# CSS and JavaScript
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
<IfModule mod_headers.c>
Header append Cache-Control "public"
</IfModule>
</IfModule>
In GTmatrix in Google pagespeed I have 100% but on Yslow the "Add Expires headers" is 0. I've tried everything but I can't seem to make Yslow work.
Can someone help?
Thanks.
You're setting the expiration to be in the past, which means they expire straight away. The idea behind adding expires headers is that you tell the browser that it doesn't even need to make an http request at all for this resource until some date in the future, instead it should just use the cached copy.
Probably only a good idea to use it on assets you know are not going to change. If you do end up changing an asset with a future expires date you'll need to change the url to it (which you can do by adding a query string on the end like blah.css?1234.
Also check that the expires headers are definitely coming through in the response headers of the assets by inspecting them with your web inspector.

Add Expires Headers for Specific Images

All of the expires headers articles I've looked at give more or less the following solution:
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000
But it doesn't make sense to me because I know which of my images are going to change and which aren't, so I want to be able to add specific expiration dates to specific image files. How would I go about this?
You can use a FilesMatch, eg.
<FilesMatch "\.(js|css)$">
ExpiresActive on
ExpiresDefault "access plus 1 month"
</FilesMatch>
Or for some specific files:
<FilesMatch "^(example.js|sample.css)$">
ExpiresActive on
ExpiresDefault "access plus 1 month"
</FilesMatch>
Note that using ExpiresDefault for specific files will not work if you already used ExpiresByType. You need to use ExpiresByType again.
So this will NOT work (service-worker.js would still have +1 year expiry):
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
ExpiresByType application/javascript "access plus 1 year"
<FilesMatch "^(service-worker.js)$">
ExpiresDefault "access plus 0 seconds"
</FilesMatch>
</IfModule>
But this will work (service-worker.js will have +0 seconds expiry):
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
ExpiresByType application/javascript "access plus 1 year"
<FilesMatch "^(service-worker.js)$">
ExpiresByType application/javascript "access plus 0 seconds"
</FilesMatch>
</IfModule>
You might also use Header unset Expires. This would remove Expires header no matter what was set above it. You should also modify (or remove) Cache-Control header. It seems that mod_expires sets both.
<FilesMatch "^(service-worker.js)$">
Header unset Expires
Header set Cache-Control "max-age=0"
</FilesMatch>

Resources