Skip to main content
 首页 » 编程设计

nginx之使用 nginx 提供给定目录的子目录中的静态文件

2024年05月06日41pengyingh

我的服务器上有几组静态 .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

请您参考如下方法:

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

When location matches the last part of the directive’s value: it is better to use the root directive instead:

这会产生:

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; 
  }        
}