В данной заметке хочу привести примеры типовой настройки файла .htaceess для веб-сервера Apache, которые реализуют включение сжатия и использование кеширования браузера для Google PageSpeed Insights (GPSI)
Это лишь та часть настроек, которую можно выполнить редактируя файл .htaccess и 100 очков по GPSI это не дает.
Использование кеширования браузера:
<ifModule mod_headers.c> <FilesMatch "\.(js|css|xml|gz)$"> Header append Vary: Accept-Encoding </FilesMatch> <FilesMatch "\.(html|htm)$"> Header set Cache-Control "max-age=43200" </FilesMatch> <FilesMatch "\.(js|css|txt)$"> Header set Cache-Control "max-age=604800" </FilesMatch> <FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|png)$"> Header set Cache-Control "max-age=2592000" </FilesMatch> <FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$"> Header unset Cache-Control </FilesMatch> </IfModule>
Использование кеширования браузера:
<IfModule mod_expires.c> <FilesMatch ".(jpg|jpeg|gif|png|ico|css|js)$"> ExpiresActive on ExpiresDefault "access plus 1 month" </FilesMatch> ExpiresDefault "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType text/html "access plus 1 month" ExpiresByType text/x-javascript "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/x-icon "access plus 1 month" ExpiresByType application/x-shockwave-flash "access plus 1 month" ExpiresByType image/gif A2592000 ExpiresByType image/jpeg A2592000 ExpiresByType image/png A2592000 BrowserMatch "MSIE" brokenvary=1 BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1 BrowserMatch "Opera" !brokenvary SetEnvIf brokenvary 1 force-no-vary </IfModule>
Включение сжатия:
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html text/plain text/xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript <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>
Хотел бы отдельно обратить внимание несколько моментов:
-
Следующие конструкции являются условными, и будут выполняться только в том случае если соответствующий модуль Apache у вас установлен. Заключать инструкции вне этих конструкций, опасно тем, что может привести к ошибкам, в том случае, когда соответствующий модуль Apache у вас не подключен.
<IfModule mod_deflate.c> </IfModule>
- Перед тем, как производить настройки, стоит проверить какие модули Apache у вас фактически включены. Для корректной работы вам потребуются модули deflate_module, expires_module, headers_module.
****@********* ~ # apache2ctl -M Loaded Modules: core_module (static) log_config_module (static) logio_module (static) version_module (static) mpm_prefork_module (static) http_module (static) so_module (static) actions_module (shared) alias_module (shared) auth_basic_module (shared) authn_file_module (shared) authz_default_module (shared) authz_groupfile_module (shared) authz_host_module (shared) authz_user_module (shared) autoindex_module (shared) deflate_module (shared) dir_module (shared) env_module (shared) expires_module (shared) headers_module (shared) include_module (shared) mime_module (shared) security2_module (shared) negotiation_module (shared) php5_module (shared) reqtimeout_module (shared) rewrite_module (shared) rpaf_module (shared) setenvif_module (shared) status_module (shared) unique_id_module (shared) vhost_alias_module (shared) ispmgr_module (shared) Syntax OK
Проверить какие модули включены можно командой apache2ctl -M. Включить и выключить модуль, командами a2enmod и a2dismod
****@********* ~ # a2enmod Your choices are: actions alias asis auth_basic auth_digest authn_alias authn_anon authn_dbd authn_dbm authn_default authn_file authnz_ldap authz_dbm authz_default authz_groupfile authz_host authz_owner authz_user autoindex cache cern_meta cgi cgid charset_lite dav dav_fs dav_lock dbd deflate dir disk_cache dump_io env expires ext_filter fcgid file_cache filter headers ident imagemap include info ldap log_forensic mem_cache mime mime_magic mod-security negotiation passenger php5 php5_cgi proxy proxy_ajp proxy_balancer proxy_connect proxy_ftp proxy_http proxy_scgi reqtimeout rewrite rpaf setenvif speling ssl status substitute suexec unique_id userdir usertrack vhost_alias Which module(s) do you want to enable (wildcards ok
После включения или выключения модуля, веб-сервер стоит перезапустить командой
service apache2 restart
- Часто на серверах работает связка Apache + nginx и кеширование статики отдают именно nginx. В таком случае, для nginx следует добавить по каждому из сайтов следующие правила.
server { ... location ~* ^.+\.(rss|atom|jpg|jpeg|gif|png|ico|rtf|js|css)$ { expires max; } ... }
Эти правила установят заголовок Cache-control, который позволит сохранить файлы по этой маске в кеш, чтобы при повторном обращении браузер использовал файлы из кеша и не загружал их снова.
Это далеко не вся информация, по настройке веб-сервера, для того, чтобы удовлетворить проверке сервиса GPSI. Если данной информации вам показалось не достаточно, и вы хотите продолжить изучение вопроса, то рекомендую ознакомиться со следующими статьями, которые описывают возможность внедрения модуля для Apache написанного компанией Google. Лично пока не экспериментировал с этим модулем, но вероятно именно с ним можно сделать так, что по PageSpeed Insights сайт отдавал 100 очков.
https://www.ibm.com/developerworks/ru/library/l-apache-pagespeed/index.html
https://www.8host.com/blog/optimizaciya-raboty-sajta-s-pomoshhyu-modulya-mod_pagespeed-v-centos-i-fedora/