I want to speed up my website. I was wondering I've done it correctly syntax wise.
<IfModule mod_expires.c>
Header unset Pragma
FileETag None
Header unset ETag
ExpiresActive On
ExpiresDefault "access plus 1 year"
##### DYNAMIC PAGES
<FilesMatch "\\.(ast|php)$">
ExpiresDefault A7200
Header set Cache-Control "public, max-age=3600, must-revalidate"
</FilesMatch>
##### STATIC FILES
<FilesMatch "(?i)^.*\.(ico|png|gif|jpg)$">
Header unset Last-Modified
Header set Expires "Fri, 21 Dec 2012 00:00:00 GMT"
Header set Cache-Control "public, no-transform"
</FilesMatch>
<FilesMatch "\\.(css|js|xml)$">
Header set Cache-Control "public, max-age=604800, must-revalidate"
</FilesMatch>
</IfModule>
Do not cache asp or php or any dynamic page! This will cause unpredictable result.
Here's an example, say you have a page called catalog.php that renders the product catalog with uptodate price and stock availability. Since you have set it to cache the result on browser for an hour, it will show stale data on browser for an hour!
Dynamic pages should never be cached wholesale like this. You need to put individual caching logic on pages based on how fresh the data should be returned from the page.
For static pages though you can do such wholesale expiration. However, be careful that if you set css and js files to expire after one year, a user who visits your site today will not fetch latest js and css from webserver for many days or months. If you make changes to the scripts or style, they will not see the changes unless you use some unique querystring to change the url of the files manually.
I have discussed an approach here that works for ASP.NET only. But it tells you about the dos and don'ts.
http://omaralzabir.com/automatic-javascript-css-versioning-to-refresh-browser-cache/
You can also read my 7 tips for making best use of caching that explains all such approaches and pros and cons of each:
http://omaralzabir.com/making_best_use_of_cache_for_high_performance_website/
Let me know if this helps.
I am aware the question is from 2011 but even then, Pragma was old. I think it is safe to stop using it.
We rarely need to set 'public' or must-revalidate unless your trying to support really old browsers and proxies like pre IEv4 and stuff.
If your going to cache your php you still need to do some work in your php code too.
Unsetting your Last-Modified for images and stuff is essentially causing a 'never cache' situation for those files until the predetermined date of the static (at the time) future date. I would think you want to cache static files X days in future always and not unset last modified.
Your htaccess file can be made to be much simpler. Borrowing some snippets from H5BP we can modernize it a bit to become:
## set some mime types to their proper types
AddType application/javascript js jsonp
AddType application/json json
AddType application/xml rss atom xml rdf
AddType image/x-icon ico
<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>
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Data
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
# Feed
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
# Favicon (cannot be renamed)
ExpiresByType image/x-icon "access plus 1 week"
# images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
# CSS and JavaScript
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
</IfModule>
# ----------------------------------------------------------------------
# Prevent mobile network providers from modifying your site
# ----------------------------------------------------------------------
# The following header prevents modification of your code over 3G on some
# European providers.
# This is the official 'bypass' suggested by O2 in the UK.
<IfModule mod_headers.c>
Header set Cache-Control "no-transform"
</IfModule>
# ----------------------------------------------------------------------
# ETag removal
# ----------------------------------------------------------------------
# FileETag None is not enough for every server.
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
# Since we're sending far-future expires, we don't need ETags for
# static content.
# developer.yahoo.com/performance/rules.html#etags
FileETag None
Google has a website that will help you analyze your site. There are a number of tools and helpful analysis available with this tool.
https://developers.google.com/speed/
Related
I'm having an error on GTMetirx: Leverage browser caching for the following cacheable resources:
I have to leverage browser caching for png, jpg, woff2, gif, gzip, and js files but this code doesn't work:
## EXPIRES HEADER 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 image/svg "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES HEADER CACHING ##
But when I added the code and try to see if the error will be fixed, it's still showing the same error, can anyone help?
I guess it's already resolved since all this time passed...
But you can first check that mod_expires is enabled on your server.
Second you can check that your .htaccess is not overrided by a virtual host conf file. If you use virtual host for your domain then check in your virtual host config file that you don't have a parent directory (of the one with your expires header) with "Allowoverride All". This Allowoverride All means that the conf file override anything in the .htaccess file. Set Allowoverride to None or put your expires header in your conf file in the Directory section.
There are other ways to resolve this problem, these two points are not an exhaustive list. It's just how I solved this problem myself today. Hope it will help somebody.
I am testing my website with gtmetrix and google speed both of them suggesting me to set expire timing on my assets including css, javascript, images etc. base on suggestions of those websites I added code below to my .htaccess file:
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# 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"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
I tried 2 ways to add code above to my .htaccess file:
first I add it to my existed code inside <IfModule
mod_rewrite.c> result was same as before
second i add it as separate code out of <IfModule
mod_rewrite.c> and still i get error to set my expire timing.
Questions
What Is correct way to add expire timing to my assets?
How do I use cookie-free domains on my stylesheets and JavaScript files as it remanded to me?
I have a very bizarre error occurring with my symfony 3 project. After doing some research I've narrowed down the error to being something to do with my system wide cache.
Why its not symfony related...
I will explain why, but before you think its something else to do with symfony or assetic cache issues read below:
I run the following shell script every-time I deploy to make sure everything is clean for production and dev environment.
chown -R distribution:distribution .
rm -rf var/cache/dev/*
rm -rf var/cache/prod/*
rm -rf web/css/*
rm -rf web/js/*
bin/console cache:clear --env=dev
bin/console cache:clear --env=prod --no-debug
bin/console assets:install web --symlink
bin/console assetic:dump --env=dev
bin/console assetic:dump --env=prod --no-debug
bin/console doctrine:schema:update --force --dump-sql
bin/console doctrine:schema:update --force --dump-sql --env=prod
chown -R distribution:distribution .
bin/console server:run
I test the dev environment by going to localhost on my computer through an SSH Tunnel.
sudo ssh -L 3306:127.0.0.1:3306 -L 80:127.0.0.1:80 -L 8000:127.0.0.1:8000 -p 25000 fake_super_user_name#(server ip address here)
The symfony development version I can access at anytime by going to my browser now and typing localhost:8000
Everything was working up until I did some major changes regarding adding a bundle in and changing the names of routes and files and there locations etc...
Why its system related...
In google chrome when I go to my page and open up the inspector, I can see its trying to access a file compiled-js_part_1_admin_1.js. This is an older version of the javascript file I had. However when I go to the server and look in my FTP program and via console with ls -al in the web/js directory that file does not exist! The correct file is compiled-js_part_2_admin_1.js, but the file referenced is in no way on my server. Therefore its grabbing a cached copy from somewhere on my computer.
So delete the cache in my browser...
This works for my production site at the actual domain name but for some reason when I try to delete the cache with localhost or entirely from Google Chrome nothing seems to delete and it keeps referencing the old file. I can see this in the cache still also by typing about:cache in the url in chrome. If you are curious how I attempted to delete cache, I open the inspector and hold down on the refresh button and select 'empty cache and hard reload'.
Okay so use another browser...
I used Firefox, Safari, and even Opera and all of them even when I have never used that browser before still are requesting the old file when I access via localhost...
I'm guessing its stored in some kind of super cache because its localhost... I have no idea where this is cache is on the system and how to remove it.
In case it matters here is my .htaccess file on the server which does set expiration and caching rules for the files... I was actually trying to test this so I didn't want to disable it, but I'm sure this is the reason its caching, I just want to figure out how to clear cache for localhost so I can develop again knowing I'm seeing the right assets.
.htaccess
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the app.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by Apache
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/app.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite all other queries to the front controller.
RewriteRule ^ %{ENV:BASE}/app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 302 ^/$ /app.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>
# These rules need to be at the bottom!
# Make it aware of True Type Fonts for Web Fonts.
AddType application/x-font-ttf .ttf
Header unset Pragma
FileETag None
Header unset ETag
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/js "access 1 week"
ExpiresByType application/javascript "access 1 week"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
Short Version
If I'm missing any information needed to solve this let me know and I'll post it right away. Short story, somehow my local system is storing cache that I can not delete. How do I delete this cache that is particular to localhost across all browsers?
Okay I found the solution...but only sort of. Assetic was giving a real error, and fixing that error made the cache start to fix it's self.
None the less, this was very strange cache behavior in this scenario.
I am using webpagetest to know my website performance.I am found issue with Cache static content i.e. "Leverage browser caching of static assets: 88/100"
FAILED - (No max-age or expires)
How can i fix the issue ?
My htaccess looks like:
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/png
AddOutputFilterByType DEFLATE image/jpg
AddOutputFilterByType DEFLATE image/gif
# Or, compress certain file types by extension:
<ifModule mod_deflate.c>
<filesMatch ".(js|css|html|htm|php|jpg|jpeg|woff|eot)$">
SetOutputFilter DEFLATE
</FilesMatch>
</ifModule>
# Direct Apache to send all HTML output to the mod_pagespeed output handler.
AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html
Thanks
In addition to the deflate settings, you want to add some expiration control to manage the browser caching. I've used the following with good results. Depending on the specifics of the files on your site you might also want to add audio and video files.
From memory, webpagetest likes it when you set the expiry to at least 1 month so you might want to also up tweak the 1 week settings
Good luck!
################
# Enable expiration control
ExpiresActive On
# Default expiration: 1 hour after request
ExpiresDefault "now plus 1 hour"
# CSS and JS expiration: 1 week after request
ExpiresByType text/css "now plus 1 week"
ExpiresByType application/javascript "now plus 1 week"
ExpiresByType application/x-javascript "now plus 1 week"
# Image files expiration: 1 month after request
ExpiresByType image/bmp "now plus 1 month"
ExpiresByType image/gif "now plus 1 month"
ExpiresByType image/jpeg "now plus 1 month"
ExpiresByType image/jp2 "now plus 1 month"
ExpiresByType image/pipeg "now plus 1 month"
ExpiresByType image/png "now plus 1 month"
########## End - Optimal expiration time
ExpiresActive on
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "now plus 0 second"
<FilesMatch "\.(css|js|png|bmp|ico|htm|gff|html|js|jpg|jpeg|gif|gcf)$">
FileETag MTime Size
ExpiresDefault "access plus 1 month"
</FilesMatch>
here is what I have in .htaccess after changing in caches control on my hosting. But even I changed those, it doesn't seem to have any good effect when I run webpagetest.org. I need to wait till the previous caches expire and run it again. It work. hurray!
. here I found a helpful link.
http://httpd.apache.org/docs/current/mod/mod_expires.html
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
A friend of mine built me a htaccess file and I'm way too much of a noobie at the moment to be able to read and know that it does (exactly). All I know is that it's supposed to do gzip compression and cache my site. When I do a speed test, it says that "Compress gzip" and "Use browser caching", which I was told the htaccess file is supposed to do. It's for a basic HTML website, nothing crazy but I just wanted to clean up some speed issues. Anyway, here is the code for it. If anyone can take a look at it and tell me what's wrong, I would truly appreciate it. If you need more information, I will be happy to post it. Thanks guys!
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x- javascript application/javascript
</ifmodule>
<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|xml|txt|css|js)$
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>
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType text/html "access 2 day"
ExpiresByType text/css "access 2 day"
ExpiresByType application/javascript "access 1 month"
ExpiresByType text/plain "access 1 month"
ExpiresByType image/jpeg "access 1 month"
ExpiresByType image/jpg "access 1 month"
ExpiresByType image/gif "access 1 month"
ExpiresByType image/png "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresDefault "access 2 days"
</IfModule>
<ifModule mod_headers.c>
Header set Connection keep-alive
</ifModule>
Check if the modules (deflate, gzip, etc) are enabled in your httpd.conf file.