在Apache 2中使用路由和静态文件调整转发到Flask应用程序



有一个Flask Application运行在http://servername.com:5000/上。它封装了gis_webapp/static/...中提供的一些Bootstrap和静态文件,这些文件按其应有的方式工作。

这是项目树:

gis_webapp
├── __init__.py
├── routes.py
├── gunicorn_gis_webapp_conf.py
├── static
│   ├── bootstrap-4.6.0-dist
│   │   ├── css
│   │   └── js
│   ├── css
│   │   └── style.css
│   └── img
│       ├── favicon.png
│       └── glogo.gif
└── templates
├── about.html
├── base.html
├── contact.html
├── errors
│   └── 404.html
├── index.html
└── result.html

一旦我通过Apache2与运行在同一服务器上的mod_auth_gssapi通过http://servername.com/(http://servername.com:80/)应用转发,使用必须继承http://servername.com:5000/的全部内容的http://servername.com/gis/,以下事情停止工作:

  1. 路由间通信

    当我点击导航栏中的联系人链接时,它会将我带到http://servername.com/contact/(不存在)而不是http://servername.com/gis/contact

  2. /static文件夹中的内容

  3. gis_webapp/static/bootstrap-4.6.0-dist文件夹引导

我做错了什么?

.conf文件的内容如下:

<VirtualHost *:80>
<Location /gis/>
ProxyPass "http://localhost:5000/"
ProxyPassReverse "http://localhost:5000/"
</Location>
</VirtualHost>

我在这些线程中找到了一些建议,并尝试应用这些建议:

  • 使用url_for链接到Flask静态文件

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap-4.6.0-dist/css/bootstrap.min.css') }}">
    
  • 使用root_path参数在Flask

    gis_webapp = Flask(__name__, root_path=os.getcwd())
    
  • 从父文件夹链接样式表

    <link rel="icon" type="image/png" href="../static/img/favicon.png">
    
  • Flask: files in static folder cannot reached (404)

    gis_webapp = Flask(__name__,
    static_url_path='',
    static_folder='static',
    template_folder='templates')
    

不幸的是他们不能解决我的问题。

我还试图修改我的routes.py文件中的路径。

# main page
@gis_webapp.route("/", methods=["GET"])
@gis_webapp.route("/index", methods=["GET"])
def index():
return render_template("index.html", title="GIS")

被改写为:

# main page
@gis_webapp.route("/gis/", methods=["GET"])
@gis_webapp.route("/gis/index", methods=["GET"])
def index():
return render_template("index.html", title="GIS")

我也发现这个线程通过apache服务静态文件,建议应用ALIAS,但它不是我的解决方案,因为后来Apache2和Flask应用程序将在不同的服务器上。然而,有一种观点:认为静态数据需要由Apache分发,即使您将其分散到不同的服务器上,那么最好将静态数据挂载到Apache所在的位置。


目前我可以部分解决2.3。在'base.html'中进行调整的问题,所以这个参考:

<link rel="icon" type="image/png" href="/static/img/favicon.png">

更改为:

<link rel="icon" type="image/png" href="/gis/static/img/favicon.png">

所以,之后我可以在http://servername.com/gis/页面上看到/static文件夹的内容,但当我打开它时它消失了,虽然http://servername.com:5000/…不明白为什么。什么好主意吗?

解决方案是按照本文的建议部署SCRIPT_NAME变量和Gunicorn:

SCRIPT_NAME="/gis" gunicorn --bind=0.0.0.0:5000 gis_webapp:gis_webapp

之后,我可以通过http://servername.com/gis/

访问应用程序然而,最初的URL http://servername.com:5000/产生了Internal Server Error。要克服它,只需使用http://servername.com:5000/gis/.

最新更新