【问题标题】:django serve media files on both apache and nginxdjango 在 apache 和 nginx 上提供媒体文件
【发布时间】:2026-02-13 00:25:01
【问题描述】:

我将进入 django 项目的生产模式,但遇到了一个特殊问题。我正在通过 apahce+mod_wsgi 运行我的 django,并通过 nginx 提供静态文件。

但是我的情况要求我不能从 nginx 提供“所有”静态文件。只需要从 apache 提供“open-flash-chart.swf”。该项目使用 openpyc 并嵌入了 open-flash-chart.swf,它需要在与 django 相同的服务器上运行,在我的例子中是 Apache。 我怎样才能做到这一点?我需要对 Apache 配置文件进行哪些更改?

server {
listen   80 default;
server_name  localhost;

access_log  /var/log/nginx/localhost.access.log;

location / {
    proxy_pass http://localhost:8080;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    client_max_body_size 10m;
    client_body_buffer_size 128k;
    proxy_connect_timeout 90;
    proxy_send_timeout 90;
    proxy_read_timeout 90;
    proxy_buffer_size 4k;
    proxy_buffers 4 32k;
    proxy_busy_buffers_size 64k;
    proxy_temp_file_write_size 64k; 
}
location /media/ {
    root /srv/www/enpass/;
    expires max;
}
}

【问题讨论】:

  • 发布您网站的 nginx 配置文件。配置可能非常不同

标签: django apache nginx static-files


【解决方案1】:

在 Apache 中,在您的虚拟主机中设置一个别名以直接提供此文件:

Alias /url/to/open-flash-chart.swf /full/path/to/open-flash-chart.swf

那么,不要使用{{ MEDIA_URL }}来引用文件,而是绝对路径中的代码:

<object data="/url/to/open-flash-chart.swf" />

Nginx 仍然会代理请求(因为它不是您的媒体路径),然后 Apache 会将文件传递回 nginx。

或者,不推荐,但如果它必须直接从 Apache 到浏览器,您可以指定端口:

<object data="http://servername:8080/url/to/open-flash-chart.swf" />

【讨论】:

    【解决方案2】:

    你需要改变 nginx 配置来处理

    /path/to/open-flash-chart.swf 
    

    对于 apache,与 / (root) 的方式相同

    【讨论】:

    • open-flash-chart 应该从 Apache 运行。其余文件将由 nginx 处理。