使用Apache2部署Django时如何修改媒体文件访问URL?
媒体文件访问路径修改后出现404错误的问题及解决
问题详情
我有一个已上线的网站,原本可正常提供媒体文件服务。
原settings.py媒体配置:
MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
项目内创建了media文件夹存储所有媒体文件,之前媒体文件访问地址为https://domain_name/media/file_name。
现在希望将访问地址改为https://domain_name/images/file_name,于是修改了settings.py配置:
MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
但修改后图片出现404错误。我使用Apache2作为Web服务器,当前Apache配置如下:
Alias /static /path_to_the_project/static <Directory /path_to_the_project/static> Require all granted </Directory> Alias /media /path_to_the_project/media <Directory /path_to_the_project/media> Require all granted </Directory> Alias /media /path_to_the_project/images <Directory /path_to_the_project/images> Require all granted </Directory> <Directory /path_to_the_project/clorrr_tailors> <Files wsgi.py> Require all granted </Files> </Directory>
模板中访问图片的代码:
<img src="{{object.image.url}}">
解决步骤
1. 修正Apache配置
当前Apache配置存在两个问题:一是重复定义了Alias /media,二是没有为新的访问路径/images配置别名映射。需要删除无效的别名,新增对应/images的映射规则,让Apache将/images的请求指向实际存储文件的media目录。
修改后的Apache配置:
Alias /static /path_to_the_project/static <Directory /path_to_the_project/static> Require all granted </Directory> # 新增别名,将/images路径映射到实际的媒体文件存储目录 Alias /images /path_to_the_project/media <Directory /path_to_the_project/media> Require all granted </Directory> <Directory /path_to_the_project/clorrr_tailors> <Files wsgi.py> Require all granted </Files> </Directory>
2. 重启Apache服务
修改配置后,必须重启Apache使新配置生效:
sudo systemctl restart apache2
3. 验证访问
模板中使用的{{object.image.url}}会自动生成新的访问路径/images/file_name,无需修改模板代码。配置生效后,即可正常访问媒体文件。若仍无法访问,可尝试清除浏览器缓存后强制刷新页面(Ctrl+F5)。
额外说明
MEDIA_ROOT是媒体文件的物理存储路径,因为文件仍存放在media目录下,所以无需修改该配置。MEDIA_URL是对外暴露的访问URL路径,修改后需确保Web服务器的别名映射与之对应。
内容的提问来源于stack exchange,提问作者Manoj Kamble
相关产品推荐
相关产品推荐

