Nginx共享目录
1、成功范例:
想在自己的服务器上共享一些文件。打算采用Http
的这种模式共享
本打算用apache
来共享,但是配了一下也没成功。
所以打算用Nginx
来配置。
也费了很多的周折,才实验成功。
配置很简单:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /img {
alias /var/ftp;
autoindex on;
}
这里配置的是img
目录,指向的是系统系统的/var/ftp
目录。
没错,我这里指向的是vsftp
共享的默认目录。
这里最最重点的是要用alias
指令,指向/var/ftp
而不是root
指令。
2、location,root,alias指令
nginx
指定文件路径有两种方式root
和alias
,指令的使用方法和作用域:
- [root]
语法:root path
默认值:root html
配置段:http
、server
、location
、if
- [alias]
语法:alias path
配置段:location
root
与alias
主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。
root的处理结果是:root路径+location路径
alias的处理结果是:使用alias路径替换location路径
alias是一个目录别名的定义,root则是最上层目录的定义。
还有一个重要的区别是alias后面必须要用“/”结束,否则会找不到文件的。。。而root则可有可无~~
root实例:
location ^~ /t/ {
root /www/root/html/;
}
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。
alias实例:
location ^~ /t/ {
alias /www/root/html/new_t/;
}
如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。注意这里是new_t,因为alias会把location后面配置的路径丢弃掉,把当前匹配到的目录指向到指定的目录。
注意:
- 使用alias时,目录名后面一定要加”/“。
- alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
- alias只能位于location块中。(root可以不放在location中)
3、显示配置
如上的设置,要想设置nginx的目录浏览功能,必须要打开下面这个参数autoindex on
;
此外,另外两个参数最好也加上去:autoindex_exact_size off
;
默认为on,显示出文件的确切大小,单位是bytes。
改为off后,显示出文件的大概大小,单位是kB或者MB或者GB
autoindex_localtime on
;
默认为off,显示的文件时间为GMT时间。
改为on后,显示的文件时间为文件的服务器时间
该模块有以下几个命令:
命令 | 默认值 | 值域 | 作用域 | EG |
---|---|---|---|---|
autoindex | off | on:开启目录浏览; off:关闭目录浏览 | http, server, location | autoindex on; 打开目录浏览功能 |
autoindex_format | html | html、xml、json、jsonp 分别用这几个风格展示目录 | http, server, location | autoindex_format html; 以网页的风格展示目录内容。该属性在1.7.9及以上适用 |
autoindex_exact_size | on | on:展示文件字节数; off:以可读的方式显示文件大小 | http, server, location | autoindex_exact_size off; 以可读的方式显示文件大小,单位为 KB、MB 或者 GB,autoindex_format为html时有效 |
autoindex_localtime | off | on、off:是否以服务器的文件时间作为显示的时间 | http, server, location | autoindex_localtime on; 以服务器的文件时间作为显示的时间,autoindex_format为html时有效 |
location /download
{
root /home/map/www/; #指定目录所在路径
autoindex on; #开启目录浏览
autoindex_format html; #以html风格将目录展示在浏览器中
autoindex_exact_size off; #切换为 off 后,以可读的方式显示文件大小,单位为 KB、MB 或者 GB
autoindex_localtime on; #以服务器的文件时间作为显示的时间
charset utf-8,gbk; #展示中文文件名
}