利用 Apache 配置提升 SEO 的实操清单
一 核心原则与优先级
二 HTTPS 与 HTTP/2 配置
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Protocols h2 http/1.1
# 可选:隐藏版本
ServerTokens Prod
ServerSignature Off
</VirtualHost>
部署命令示例:sudo certbot --apache -d example.com -d www.example.com;Debian/Ubuntu 可启用模块:sudo a2enmod ssl。
三 URL 重写与规范化
RewriteEngine On
RewriteBase /
# 统一域名与协议(放在最前,避免循环)
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]
# 前端控制器
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
# 伪静态
RewriteRule ^article/([0-9]+)/?$ article.php?id=$1 [L]
排查要点:确认模块启用、目录 AllowOverride 为 All/FileInfo、正则无歧义、必要时用条件避免循环。
四 性能优化 压缩与缓存
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/javascript application/json application/xml application/rss+xml \
image/svg+xml image/x-icon font/woff2 font/woff font/ttf
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/ttf "access plus 1 year"
</IfModule>
提示:对 HTML 设置较短缓存以便内容更新快速生效;对体积较大且不常变的 静态资源 设置更长缓存,并配合文件名哈希或 CDN 缓存失效策略。
五 安全头与日志监控
<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"
# 可选:根据站点策略开启 CSP
# Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.example.com"
</IfModule>
建议将日志格式设为 combined,便于分析来源、UA、耗时与响应码。