使用Nginx从给定目录的子目录中提供静态文件 [英] Use nginx to serve static files from subdirectories of a given directory

查看:601
本文介绍了使用Nginx从给定目录的子目录中提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

它应该可以工作,但是

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

当位置与指令值的最后一部分匹配时: 最好改用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆