我之前对 js/css 文件使用过类似的东西(我修改了下面的内容以满足您的需求)。将其添加到您的虚拟主机条目中:
Alias /doc/ "/usr/share/doc/"
Alias local.doc "/usr/share/doc/"
<Directory /usr/share/doc>
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
AddEncoding gzip gz
<FilesMatch "\.gz$">
ForceType text/plain
Header set Content-Encoding: gzip
</FilesMatch>
</Directory>
更新上面以匹配您的代码
在 ubuntu 中确保 Headers 模块已启用
$ sudo a2enmod headers
$ sudo a2enmod deflate
$ sudo apache2ctl restart
Update2:意识到“AddEncoding gzip gz”丢失了..否则,文件会继续尝试下载。
Update3:添加了 apache 模块 deflate 安装命令。这是我的 deflate.conf:
<IfModule mod_deflate.c>
# these are known to be safe with MSIE 6
AddOutputFilterByType DEFLATE text/html text/plain text/xml
# everything else may cause problems with MSIE 6
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript
AddOutputFilterByType DEFLATE application/rss+xml
</IfModule>
您可以首先尝试使用其他类型的文件(例如 css 文件)。例子:
cd /usr/share/doc
cat ".styles { width: 50px; }" > test.css
gzip -c test.css > test.css.gz
将其添加到您的虚拟主机:
<FilesMatch "\.css\.gz$">
ForceType text/css
Header set Content-Encoding: gzip
</FilesMatch>
Test http://127.0.0.1/doc/test.css http://127.0.0.1/doc/test.css and http://127.0.0.1/doc/test.css.gz http://127.0.0.1/doc/test.css.gz看看你得到什么结果。