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

时间:2012-10-09 19:17:20

标签: nginx static-files

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

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

.html文件位于/home/www-data/mysite/public/doc/foo/bar.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

1 个答案:

答案 0 :(得分:73)

它应该有用,但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;
  }       
}
相关问题