在 Nginx 上服务 Jekyll 博客

Serve Jekyll blog on Nginx

我正在尝试在 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 //index.html /.html =404;
}

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

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

If I remove the 404 fallback it only works for the last value.

这是因为 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>[^/]+)/?$