gpt4 book ai didi

nginx - 如何使用 nginx 为 root 和代理其他所有内容提供静态 html?

转载 作者:行者123 更新时间:2023-12-02 15:15:43 26 4
gpt4 key购买 nike

此配置的目标是:

  1. 为主页提供纯 html 以启动 SPA,例如。 www.website.com, www.website.com/?foo=bar
  2. 代理 Python REST API 以获取 1 未捕获的所有内容,例如。 www.website.com/foo, www.website.com/foo?bar=123

html 文件位于 /var/www/website.com/index.html

server {
listen 80;
server_name website.com;
return 301 $scheme://www.website.com$request_uri;
}

server {
listen 80;
server_name www.website.com;
access_log off;

location = / {
root /var/www/website.com;
}
location / {
proxy_pass http://127.0.0.1:8000;
}
}

我在 Python 端看到对 /index.html 的请求,但在那里失败了。如果我删除 location/,那么我会看到“欢迎使用 nginx”页面,很明显 location =/ 不起作用。我做错了什么?

最佳答案

NGINX - Serving Static Content

If a request ends with a slash, NGINX treats it as a request for a directory and tries to find an index file in the directory. The index directive defines the index file’s name (the default value is index.html).

检查是否定义了index在当前或任何封闭范围内。如果是这样,它会在 nginx 中创建一个内部重定向,该重定向将匹配 Python 位置 (location/)。

对于您的情况,我认为至少有两种解决方案:

  1. 添加另一个与索引文件明确匹配的位置 block :

    location = /index.html {
    ...
    }
  2. 使用 try_files在根位置:

    location = / {
    try_files $uri $uri/index.html =404;
    }

关于nginx - 如何使用 nginx 为 root 和代理其他所有内容提供静态 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com