AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript
Пропишите следующую конфигурацию в виртуальный хост Apache и это включит сжатие mod_deflate для вашего сайта.
<Directory /var/www/html/>
<IfModule mod_mime.c>
AddType application/x-javascript .js
AddType text/css .css
</IfModule>
<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
#The following line is enough for .js and .css
AddOutputFilter DEFLATE js css
AddOutputFilterByType DEFLATE text/plain text/xml application/xhtml+xml text/css application/javascript application/xml application/rss+xml application/atom_xml application/x-javascript application/x-httpd-php application/x-httpd-fastphp text/html
</IfModule>
<IfModule mod_setenvif.c>
# Удалить ошибки браузера (требуется только для очень старых браузеров)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>
<IfModule mod_headers.c>
Header append Vary User-Agent env=!dont-vary
</IfModule>
<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>
</Directory>
Используем кеш на стороне браузера в Apache
Как только пользователь откроет сайт будут скачиваться не только код страницы с html страницы, и так же css, картинки, js. И одно открытие страницы файла обращается к серверу от нескольких десятков и аж до нескольких сотен! такие запросы очень нагружают сервер, и так же дают дополнительное время на загрузку страницы у пользователя.
Создаем файл .htaccess в своей домашней директории сайта и добавляем:
# кеширование в браузере на стороне пользователя
<IfModule mod_expires.c>
#Включаем поддержку директивы Expires
ExpiresActive On
# Задаем время для хранения файлов в кэше для каждого типа
ExpiresDefault "access 7 days"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
ExpiresByType text/html "access plus 7 day"
ExpiresByType text/x-javascript "access 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType application/x-shockwave-flash "access 1 year"
</IfModule>
# Cache-Control
<ifModule mod_headers.c>
# Задаем 30 дней для данного типа файла
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
# Задаем 30 дней для данного типа файла
<filesMatch "\.(css|js)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
# Задаем 2 дня для данного типа файла
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</filesMatch>
# Задаем 1 день для данного типа файла
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=172800, private, must-revalidate"
</filesMatch>
</ifModule>
# использование кеша браузеров
FileETag MTime Size
<ifmodule mod_expires.c>
<filesmatch ".(jpg|jpeg|gif|png|ico|css|js)$">
ExpiresActive on
ExpiresDefault "access plus 1 year"
</filesmatch>
</ifmodule>
#Запрет отдачи HTTP-заголовков Vary браузерам семейства MSIE
<IfModule mod_setenvif.c>
BrowserMatch "MSIE" force-no-vary
BrowserMatch "Mozilla/4.[0-9]{2}" force-no-vary
</IfModule>
Проверка gzip и кэширования в Nginx и Apache
Если в списке нет mod_expires или mod_headers – выполните в консоли сервера (подключившись по ssh) по очереди следующие команды (это установит/включит mod_expires, mod_headers):
# a2enmod headers
# a2enmod expires
# service apache2 restart
Для индексной странички видим, что gzip включён, но для URL из js нет:
$ curl -I -H 'Accept-Encoding: gzip,deflate' https://disnetern.ru/ | grep gzip
А после добавления gzip_types получаем такое:
$ curl -I -H 'Accept-Encoding: gzip,deflate' https://disnetern.ru/
ИЛИ еще:
# curl --header "Accept-Encoding: gzip,deflate,sdch" -I http://linux-notes.org
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 25 Jun 2015 11:27:22 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: wfvt_3183169984=558be599d6523; expires=Thu, 25-Jun-2015 11:57:21 GMT; path=/; httponly
X-Pingback: http://linux-notes.org/xmlrpc.php
X-UA-Compatible: IE=edge,chrome=1
Expires: Fri, 26 Jun 2015 11:27:22 GMT
Cache-Control: max-age=86400
Pragma: public
Cache-Control: max-age=86400, public, must-revalidate, proxy-revalidate
Content-Encoding: gzip
Для того, чтобы включить .htaccess в Apache2, надо отредактировать /etc/apache2/sites-available и называется 000-default.conf (по-умолчанию, если на сервере один сайт).
<Virtualhost *:80>
ServerAdmin admin@site.com
DocumentRoot /var/www
<Directory /var/www>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</Virtualhost>
Перезагружаем apache:
service apache2 reload
Всё. Теперь Ваш .htaccess работает в любой под директории /var/www
Ключевым параметром в данном случае является AllowOverride All. Также можете найти и поправить секцию Directory в /etc/apache2/apache2.conf.
Вконтакте
Facebook
Google+
LiveJournal
LinkedIn
Одноклассники
E-mail
Pinterest
Мой мир
Comments
So empty here ... leave a comment!