如何在AWS EC2的Ubuntu+Apache环境下实现Flask图片展示
问题核心原因
- Apache仅配置了
/nextstep路由转发给Flask处理,未配置静态资源路径映射,无法正确识别static目录下的资源请求 - Flask应用挂载在
/nextstep二级路径下,直接使用相对路径拼接静态资源地址缺少前缀,请求路径不匹配 - 浏览器只识别Web服务路径,你在HTML里写的服务器本地文件路径完全无效
- 软链接对应的源目录可能缺少Apache运行用户(www-data)的读取权限
修复步骤
1. 修正Apache配置
编辑/etc/apache2/sites-available/000-default.conf,替换nextstep相关配置块为以下内容:
WSGIDaemonProcess nextstep threads=5 WSGIScriptAlias /nextstep /var/www/html/nextstep/nextstep.wsgi # 新增静态资源别名映射 Alias /nextstep/static /var/www/html/nextstep/static <Directory /var/www/html/nextstep/static> Require all granted </Directory> <Directory /var/www/html/nextstep> WSGIProcessGroup nextstep WSGIApplicationGroup %{GLOBAL} Require all granted </Directory>
注:原配置中的Order deny,allow是Apache 2.2版本语法,替换为2.4及以上版本通用的Require all granted避免兼容问题。
2. 修正Flask代码
修改nextstep.py,使用Flask自带的url_for函数生成静态资源路径,自动适配应用挂载前缀:
from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def hello_world(): user_image = url_for('static', filename='mouse.jpg') return render_template('nextstep.html', user_image=user_image) if __name__ == '__main__': app.run()
原代码中的UPLOAD_FOLDER配置未实际使用,可直接删除。
3. 简化HTML代码
修改nextstep.html,删除所有无效的img标签,仅保留用变量生成的资源引用即可:
<html> <body> Hello World from nextstep.html {{ user_image }} <a href="nextstep2">next step 2</a> <img src="{{ user_image }}" alt="User Image"> </body> </html>
4. 修复目录权限
执行以下命令给Apache运行用户开放静态目录读取权限:
sudo chmod -R 755 /home/ubuntu/nextstep/static sudo chown -R www-data:www-data /home/ubuntu/nextstep/static
5. 重启Apache生效配置
sudo systemctl restart apache2
修复完成后访问你的服务器地址/nextstep即可正常加载图片。
内容的提问来源于stack exchange,提问作者Danny
相关产品推荐
相关产品推荐

