Ubuntu上Apache2配置SEO实用技巧
一 基础配置与HTTPS
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com/public_html
SSLEngine on
SSLCertificateFile /path/to/cert.crt
SSLCertificateKeyFile /path/to/private.key
SSLCertificateChainFile /path/to/chain.crt
# 安全与合规
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
# 可选:隐藏Apache版本
ServerTokens Prod
ServerSignature Off
<Directory /var/www/example.com/public_html>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</IfModule>
要点:启用SSL并做301跳转、设置HSTS、隐藏版本信息,有助于排名与安全性。二 URL结构与重写
# 1) HTTP→HTTPS(若未在80端口做全局跳转)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 2) 旧页→新页 301
RewriteRule ^old-page$ /new-page [R=301,L]
# 3) 前端控制器(如Laravel、自研MVC)
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# 4) 文章友好URL:/article/123/my-title → article.php?id=123&title=my-title
RewriteRule ^article/([0-9]+)/([a-zA-Z0-9-]+)$ article.php?id=$1&title=$2 [L,QSA]
要点:使用mod_rewrite实现语义化URL与301重定向,避免重复内容并提升可抓取性。三 性能与压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/javascript application/json application/x-javascript
# 可选:为字体与常见资源开启压缩
AddOutputFilterByType DEFLATE application/font-woff application/font-woff2 \
application/font-truetype application/font-opentype
# 避免对图片等已压缩类型再压缩
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|pdf|zip|rar)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary
</IfModule>
四 可维护性与上线检查