【问题标题】:Use nginx to serve static files from subdirectories of a given directory使用 nginx 从给定目录的子目录中提供静态文件
【发布时间】:2012-09-30 04:32:42
【问题描述】:

我的服务器上有几组静态 .html 文件,我想使用 nginx 直接为它们提供服务。例如,nginx 应该提供以下模式的 URI:

www.mysite.com/public/doc/foo/bar.html

使用位于/home/www-data/mysite/public/doc/foo/bar.html.html 文件。您可以将foo 视为集合名称,将bar 视为此处的文件名。

我想知道以下 nginx 配置是否可以完成这项工作:

server {
    listen        8080;
    server_name   www.mysite.com mysite.com;
    error_log     /home/www-data/logs/nginx_www.error.log;
    error_page    404    /404.html;

    location /public/doc/ {
        autoindex         on;
        alias             /home/www-data/mysite/public/doc/;
    }

    location = /404.html {
        alias             /home/www-data/mysite/static/html/404.html;
    }
}

换句话说,/public/doc/.../....html 模式的所有请求都将由 nginx 处理,如果找不到任何给定的 URI,则返回默认的 www.mysite.com/404.html

【问题讨论】:

    标签: nginx static-files


    【解决方案1】:

    它应该可以工作,但是 http://nginx.org/en/docs/http/ngx_http_core_module.html#alias 说:

    当 location 与指令值的最后一部分匹配时: 最好使用 root 指令:

    这会产生:

    server {
      listen        8080;
      server_name   www.mysite.com mysite.com;
      error_log     /home/www-data/logs/nginx_www.error.log;
      error_page    404    /404.html;
    
      location /public/doc/ {
        autoindex on;
        root  /home/www-data/mysite;
      } 
    
      location = /404.html {
        root /home/www-data/mysite/static/html;
      }       
    }
    

    【讨论】:

    • 在过去使用 2 个根给我带来了问题,我通常做的是像 @AlessioCampanelli 建议的那样为其他位置使用一个根和别名
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多