Apache配置优化移动端体验的实用方案
一 网络传输与缓存优化
<IfModule mod_deflate.c>
DeflateCompressionLevel 6
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript application/json
AddOutputFilterByType DEFLATE application/xml application/xhtml+xml
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE\s(7|8) !no-gzip !gzip-only-text/html
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 hour"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/json "access plus 0 seconds"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(ico|jpe?g|png|webp|css|js)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
KeepAlive On
MaxKeepAliveRequests 150
KeepAliveTimeout 5
二 并发与MPM调优
httpd -V | grep -i mpm,根据模式调整并发与资源。<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 400
</IfModule>
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
三 按需跳转与设备适配
RewriteEngine On。# 例:?mobile=1 或 ?mobile=0
RewriteCond %{QUERY_STRING} (?:^|&)mobile=(0|1)(?:&|$)
RewriteRule ^ - [CO=mobile:%1:%{HTTP_HOST}]
RewriteEngine On
# 若用户显式选择桌面版,则不跳转
RewriteCond %{QUERY_STRING} (?:^|&)mobile=0(?:&|$)
RewriteRule ^ - [L]
# 若Cookie不存在,按UA判定
RewriteCond %{HTTP_COOKIE} !mobile=1
RewriteCond %{HTTP_USER_AGENT} "(android|blackberry|iphone|ipod|opera mini|iemobile|mobile|webos|ucweb|windows phone|symbian|hpwOS)" [NC]
RewriteRule ^(.*)$ https://m.example.com/$1 [L,R=302]
# 可选:桌面端访问移动端时跳转回桌面
RewriteCond %{HTTP_COOKIE} mobile=1
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=302]
四 媒体与资源正确交付
video/mp4、video/webm),否则移动端可能无法播放或无法触发硬件解码。preload="metadata" 优化首帧体验,但移动端可能忽略以节省流量。五 落地与验证