使用 nginx 从给定目录的子目录中提供静态文件 [英] Use nginx to serve static files from subdirectories of a given directory
问题描述
我的服务器上有几组静态 .html
文件,我想使用 nginx 直接为它们提供服务.例如,nginx 应该提供以下模式的 URI:
I have several sets of static .html
files on my server, and I would like use nginx to serve them directly. For example, nginx should serve an URI of the following pattern:
www.mysite.com/public/doc/foo/bar.html
使用位于 /home/www-data/mysite/public/doc/foo/bar.html
的 .html
文件.您可以将 foo
视为集合名称,将 bar
视为此处的文件名.
with the .html
file that is located at /home/www-data/mysite/public/doc/foo/bar.html
. You can think of foo
as the set name, and bar
as the file name here.
我想知道以下 nginx 配置是否可以完成这项工作:
I wonder whether the following piece of nginx config would do the job:
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
.
In other words, all requests of the pattern /public/doc/.../....html
are going to be handled by nginx, and if any given URI is not found, a default www.mysite.com/404.html
is returned.
推荐答案
它应该可以工作,但是 http://nginx.org/en/docs/http/ngx_http_core_module.html#alias 说:
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
当 location 匹配指令值的最后一部分时:最好使用 root 指令代替:
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;
}
}
这篇关于使用 nginx 从给定目录的子目录中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!