Apache配置优化提升网站排名的实操清单
一 基础必做
二 关键配置示例
<VirtualHost *:443>
Protocols h2 http/1.1
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
# ... 其他站点配置
</VirtualHost>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/javascript application/json application/xml image/svg+xml
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "public, max-age=31536000" "expr=%{REQUEST_URI} =~ m#\.(jpg|jpeg|png|gif|webp|svg)$#"
</IfModule>
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-XSS-Protection "1; mode=block"
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://cdn.example.com; font-src 'self' https://fonts.gstatic.com"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L]
</IfModule>
# 将 www 统一到 non-www(或反向)
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# 将 HTTP 全部 301 到 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheIgnoreHeaders Set-Cookie
</IfModule>
</IfModule>
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
以上示例可按站点实际目录、资源类型与 CDN 策略微调。
三 部署与验证
四 常见陷阱与排查
五 影响排名的配套动作