优化Apache2的.htaccess文件可以提高网站性能、增强安全性并实现更精细的访问控制。以下是一些常见的优化建议:
通过启用Gzip压缩,可以减少传输的数据量,加快页面加载速度。
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
通过设置缓存头,可以让浏览器缓存静态资源,减少服务器负载。
<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/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
<IfModule mod_headers.c>
Header append Cache-Control "public"
</IfModule>
防止用户通过浏览器查看目录内容。
Options -Indexes
通过重写规则,可以实现更友好的URL结构,并提高搜索引擎优化(SEO)效果。
RewriteEngine On
# 隐藏index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
通过设置访问控制,可以保护敏感文件和目录。
<FilesMatch "\.(htaccess|htpasswd|ini|log)$">
Order allow,deny
Deny from all
</FilesMatch>
<Directory "/var/www/html/admin">
Order deny,allow
Deny from all
Allow from 192.168.1.1
</Directory>
通过设置安全头,可以增强网站的安全性。
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "no-referrer-when-downgrade"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; object-src 'none';"
</IfModule>
通过禁用不必要的模块,可以减少服务器的内存和CPU使用。
# 禁用不必要的模块
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule dir_module modules/mod_dir.so
LoadModule alias_module modules/mod_alias.so
通过启用KeepAlive,可以减少TCP连接的建立和关闭次数,提高性能。
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
通过调整日志记录级别和格式,可以减少日志文件的大小和生成速度。
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
ErrorLog ${APACHE_LOG_DIR}/error.log
通过使用内容分发网络(CDN),可以加速静态资源的加载速度,并减轻服务器负载。
# 假设你使用的是Cloudflare CDN
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain\.com$
RewriteRule ^(.*)$ https://cdn.yourdomain.com/$1 [P,L]
通过以上优化措施,可以显著提高Apache2服务器的性能和安全性。请根据你的具体需求和环境进行调整。