从子目录提供文件和资产

Serving files and assets from a subdirectory

我正在尝试从网站的子目录中获取文件和资产,如下所示:

站点:/go/tools/(index.html为根文件) 资产链接如下:/go/tools/assets/js/main.js

使用 nginx,我的配置如下所示:

server {
    listen 80;
    listen 443 ssl http2;
    server_name local.tools;

    index index.html;

    location /go/tools {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            root /code/testing/build;
            try_files $uri /$uri /index.html =404;
    }

当我用 url local.tools/go/tools 加载站点时,index.html 页面加载并且 html 看起来像这样:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="icon" href="assets/img/favicon.ico">
    <link href="assets/css/vendor/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>...

所以那部分很好。问题是样式和 javascript 不存在。当我查看网络选项卡时,我看到每个资产都在加载 index.html 内容而不是它自己的内容。

我的配置中缺少什么,所以如果我转到:/go/tools/assets/css/styles.css 我会看到实际的样式表吗?

您需要使用以下配置

location /go/tools {
        location /go/tools/assets/ {
            alias /code/testing/build/assets/;
        }
        alias /code/testing/build;
        try_files $uri $uri/ /index.html =404;
}

基本上当 url 是 /go/tools/assets 时,您需要从构建目录中的 /assets 进行搜索。这就是为什么我们需要在嵌套位置使用别名