Apache 本身不执行 Python 应用,需通过 mod_wsgi 或反向代理(如 mod_proxy + Gunicorn)部署;静态资源缓存加速的核心是 Apache 充当反向代理与缓存层,分离动静路径(如 /static/ 本地服务并磁盘缓存,/api/ 代理至 Python 后端),启用 mod_cache_disk、mod_expires 等模块并严格配置 CacheEnable disk /static/ 与 ExpiresByType 规则,同时用 ProxyPass "!" 排除静态路径防误代理。

Apache 本身不直接执行 Python 应用(如 Flask/Django),通常需搭配 WSGI 模块(mod_wsgi)或反向代理给 Gunicorn/uWSGI。所谓“Python 部署中配置代理缓存加速静态页面”,本质是:让 Apache 充当反向代理 + 静态资源缓存层,把动态请求转给后端 Python 服务,同时自己高效服务并缓存 CSS/JS/图片等静态内容。
明确动静分离边界
Apache 不应既跑 Python 又硬扛所有静态请求。合理做法是:
- Python 应用只暴露 API 或动态 HTML 路径(如 /api/、/admin/)
- 所有前端资源(/static/、/media/、/*.css、/*.js)由 Apache 直接提供,并启用缓存
- 根路径(/)可设为代理入口,但需前置规则拦截已存在的静态文件
启用 mod_cache 和相关模块
确保以下模块已启用(在 Ubuntu/Debian 上运行):
- mod_cache(缓存主模块)
- mod_cache_disk(磁盘缓存后端)
- mod_expires(设置过期头)
- mod_headers(自定义响应头)
- mod_proxy 和 mod_proxy_http(反向代理必需)
启用命令示例:a2enmod cache cache_disk expires headers proxy proxy_http,然后重启 Apache。
立即学习“Python免费学习笔记(深入)”;
配置静态资源缓存策略
在虚拟主机或目录配置中加入:
<IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css "access plus 1 year" ExpiresByType text/javascript "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" </IfModule> <p><IfModule mod_headers.c> Header append Cache-Control "public" Header unset ETag FileETag None </IfModule>
这样浏览器和中间代理都会缓存这些资源长达一年,减少重复请求。
配置反向代理 + 缓存动态响应(谨慎使用)
对 Python 后端返回的 HTML 页面做缓存需格外小心(避免用户看到过期登录态或个性化内容)。如确需缓存,仅限无状态、公开页面(如首页、帮助页):
CacheQuickHandler off CacheLock on CacheLockPath /var/cache/apache2/mod_cache_lock CacheIgnoreHeaders Set-Cookie <p><Location "/>" CacheEnable disk CacheIgnoreCacheControl On CacheIgnoreNoLastMod On CacheMaxFileSize 1048576 CacheMinFileSize 1 CacheIgnoreURLSessionIdentifiers PHPSESSID </Location></p><p>ProxyPass "/api/" "<a href="https://www.php.cn/link/e2a56fd6606bad270c8e5a661f919287">https://www.php.cn/link/e2a56fd6606bad270c8e5a661f919287</a>" ProxyPassReverse "/api/" "<a href="https://www.php.cn/link/e2a56fd6606bad270c8e5a661f919287">https://www.php.cn/link/e2a56fd6606bad270c8e5a661f919287</a>"</p><h1>确保静态路径不被代理</h1><p>ProxyPass "/static/" "!" ProxyPass "/media/" "!"
关键点:
- CacheQuickHandler off:强制进入完整缓存流程(否则默认跳过)
- CacheIgnoreHeaders Set-Cookie:防止因后端返回 Cookie 而拒绝缓存
- ProxyPass "/static/" "!":显式排除静态路径,避免误代理
- 不要对 /login、/user 类路径启用缓存


















