html - 我的 HTML/CSS 文件在 Nginx 上不同位置的路由有什么问题?

标签 html css nginx

我已经在 gunicorn 中实现了 flask 应用程序,它目前正在 Nginx 上运行。该应用程序的结构如下:templates 文件夹中的几个 HTML 页面(index.html、chat.html、token.html),static 中包含 CSS 文件的文件夹。

我想要的是确保当用户访问 host:port 时,他们看到的是 index.html,但是当他们访问 host:port/token 他们看到 token.html

我很确定问题出在我的 Nginx 配置上。一旦网站被访问,我本可以设法让 index.html 出现。也使用了 CSS 文件,因为 html 页面看起来并不平淡(所以这里访问 CSS 文件没有问题)。

但是,一旦我访问 host:port/token,页面就会变成空白的 HTML 代码,可以在 token.html 中找到。由于某种原因,在这种情况下,CSS 文件中的信息不适用于 HTML。

如何让 Nginx 找到我的 CSS 文件?我应该以某种方式指定静态文件的文件夹位置吗?但它适用于正常位置 (host:port),只是不适用于其他位置。我的 Nginx 配置如下:

server {

listen 7000 ssl http2 default_server;
listen [::]:7000 ssl http2 default_server;

server_name host www.host;

access_log /home/user/project/server/nginx_logs/nginx-access.log;
error_log  /home/user/project/nginx_logs/nginx-error.log;

include snippets/certs.conf;
include snippets/ssl-params.conf;

location / {
    include proxy_params;
    proxy_pass http://unix:/home/user/project/server/chat.sock;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    try_files $uri $uri/ =404;
            }

location /token {
    index token.html;
    alias /home/user/project/server/app/templates;
} }

最佳答案

你对flask app在wsgi server下的运行方式有误解,没有完全理解try_files重定向的作用。对于一个flask应用,template/中的index.html是根据你设置的flask路由生成的,它是一个模板,并不是一个静态的html文件。因此,假设您正确设置了 wsgi 服务器以运行 flask 应用程序,那么运行 flask 应用程序所需的全部 nginx 配置如下:

server {

    listen 7000 ssl http2 default_server;
    listen [::]:7000 ssl http2 default_server;

    server_name host www.host;
    root /home/user/project/app;

    access_log /home/user/project/server/nginx_logs/nginx-access.log;
    error_log  /home/user/project/nginx_logs/nginx-error.log;

    include snippets/certs.conf;
    include snippets/ssl-params.conf;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/user/project/server/chat.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

此配置基本上将所有命中根的请求传递到后端 wsgi 套接字(运行您的 flask 应用程序)。它有效,但并不理想,首先,如果您检查访问日志,您会注意到 nginx 记录每个 GET 请求,包括对位于 static/ 目录中的静态内容的 GET 请求。其次,您可能希望 nginx 直接处理这些静态内容而不将其传递给后端。因此,您经常会看到 flask 应用程序的 nginx 配置至少有一个额外的位置指令来处理静态内容:

server {
    ### all the directives as previous example ###

    location /static/ {
        alias /home/user/project/app/static/;
    }

    location / {
        ### as per previous example ###
    }

关于html - 我的 HTML/CSS 文件在 Nginx 上不同位置的路由有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844949/

相关文章:

html - 如何让文字在图片上居中?

amazon-s3 - 什么是 RESTful Web 服务最具可扩展性和高性能的 Amazon Web Service (AWS) 配置?

css - 如何使用 svg 或其他响应式解决方案制作 flex 的标题

mysql - 使用依赖库编译nginx模块

Nginx:响应处理和带缓存的反向代理

javascript - DOM 元素(例如按钮的 onclick 函数)是否需要显式发送事件作为参数?

html - 如何通过正文移动我的标题

javascript - 用星号屏蔽 HTML 表单文本字段

php - 包含数据库值和用户输入的表

HTML 表单字段和边距显示