【问题标题】:Serving static files through apache通过 apache 提供静态文件
【发布时间】:2014-07-14 15:18:57
【问题描述】:

我是整个 mod_wsgi 和通过 apache 提供文件的新手。我对烧瓶真的很满意,但这是我无法理解的。我做了hello-world程序,成功展示了hello world! 现在我想显示一个图像文件。所以我将我的 hello-world.py 更新为:

from flask import *
yourflaskapp = Flask(__name__)

@yourflaskapp.route("/")
def hello():
    file="203.jpg"
    return render_template("hello.html",file=file)
#   return"HEY"
if __name__ == "__main__":
    yourflaskapp.run()

我的目录结构类似于:/var/www/hello-world

/hello-world
    test.py
    yourflaskapp.wsgi
    /static
        -203.jpg
    /templates
        -hello.html

我的模板很简单:

<!DOCTYPE html>
<html><head><title>hi</title></head>
<body>
<img src="{{url_for('static',filename=file)}}"/>
</body></html>

我的 apache conf 文件是:

<VirtualHost *:80>
     WSGIDaemonProcess yourflaskapp
     WSGIScriptAlias / /var/www/hello-world/yourflaskapp.wsgi
     Alias /static/ /var/www/hello-world/static
     Alias /templates/ /var/www/hello-world/templates
     <Directory /var/www/hello-world>
            WSGIProcessGroup yourflaskapp
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
     </Directory>
        <Directory /var/www/hello-world/static>
            Order allow,deny
            Allow from all
        </Directory>
        <Directory /var/www/hello-world/templates>
            Order allow,deny
            Allow from all
        </Directory>
     ErrorLog ${APACHE_LOG_DIR}/error.log
     LogLevel warn
     CustomLog ${APACHE_LOG_DIR}/access.log combined
 </VirtualHost>

虽然当我打开浏览器并转到我的 ip 时,它并没有显示图像文件。 我究竟做错了什么?我应该遵循其他方法吗? 如果有人可以推荐任何我可以理解使用flask+mod_wsgi+apache2的好的链接

【问题讨论】:

  • 直接点击{your-ip}/static/203.jpg会发生什么?

标签: python static flask apache2 mod-wsgi


【解决方案1】:

在子 URL 上挂载静态文件时,平衡尾随斜杠通常总是一个好主意。所以而不是:

Alias /static/ /var/www/hello-world/static

使用:

Alias /static /var/www/hello-world/static

【讨论】:

  • 它有什么不同?
  • 因为 Apache 将从路径中删除 LHS 上匹配的内容,并将结果附加到 RHS。因此,如果有'/static/foo',在剥离'/static/'之后如果得到'foo',当添加到RHS时会尝试打开'/var/www/hello-world/staticfoo',这是' t 正确,因为斜线已被删除。我不记得它发生的确切场景,也不记得它是否与特定的 Apache 版本有关,所以只是建议你让它匹配以避免出现问题。
  • 这个解决方案有效吗?因为我面临同样的问题。谢谢。
  • @RicardoSilva 如果您还没有,只需为您的问题创建一个新问题并解释您如何拥有事物的详细信息。这比询问针对其他人问题的建议解决方案是否有效要好,因为您的问题可能完全不同,但没有任何细节,没人能说清楚。