首页 > 解决方案 > 在 Nginx 上服务 Jekyll 博客

问题描述

我正在尝试在 nginx 上提供一个 jekyll 博客。构建目录中的文件应该可以通过以下路径访问:

  - index.html -> /
  - 1.0/
    - index.html -> /1.0/
    - foo/
        a.html   -> /1.0/foo/a/
        b.html   -> /1.0/foo/b/
        c.html   -> /1.0/foo/c/
    - bar/
        1.html   -> /1.0/bar/1/
        2.html   -> /1.0/bar/2/

我尝试在 nginx 中使用 try_files 指令,但它总是调用回退,尽管文件可用。这是配置:

location ~* ^(.+)/$ {
  try_files $uri /$1/index.html /$1.html =404;
}

如果我删除 404 回退,它仅适用于最后一个值。

所以我的问题是:配置 nginx 以提供这样的静态文件的最佳方法是什么?

标签: nginxjekyllstatic-files

解决方案


如果我删除 404 回退,它仅适用于最后一个值。

这是因为try_files指令的最后一个参数应该是 HTTP 错误代码或 URI,以在未找到文件时尝试。在您的情况下,nginx 假定它是一个 URI。

试试这个:

location ~ ^(?<path>/.*/)(?<file>[^/]+)/$ {
    try_files $uri $path$file.html $uri/ =404;
}

如果您想处理http://example.com/1.0/foo/a类似于 的请求http://example.com/1.0/foo/a/,请将正则表达式更改为^(?<path>/.*/)(?<file>[^/]+)/?$.


推荐阅读