Nginx alias指令
2014-03-08 by dongnan
Nginx alias指令
开始之前
某个django项目,用户上传的文件存储在 /star/uploads目录,URI为 http://www.demo.com/attachments/mylist.csv 。
项目的静态文件(css、js、pic)存储在 /star/static目录,URI为 http://www.demo.com/static/js/jquery.js 。
项目结构
tree -L 1 -d star/
star/
├── appointment
├── star
├── static
├── templates
├── uploads
└── web
6 directories
这里使用Nginx反向代理django ,对于 URI能够匹配的/static 与/star/static目录来说,我们可以使用nginx的 root指令,例如:
location ^~ /static {
root /star/;
}
但是对于 URI不能匹配的/attachments 与 /star/uploads目录来说,我们该如何处理呢?
对啦答案就是nginx的alias指令,例如:
location ^~ /attachments {
alias /star/uploads/;
}
配置文件
cat /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name www.demo.com;
#..其它配置项目省略
# alias 到文件
location = /baidu_verify.html {
alias /star/static/baidu_verify.html;
}
# alias 到目录
location ^~ /attachments {
alias /star/uploads/;
expires 180d;
}
location ^~ /static {
root /star/;
expires 60d;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_pass http://unix:/var/run/django.socket;
proxy_redirect default;
}
}
alias
- 语法:
alias file-path|directory-path; - 默认值:
no - 使用字段:
location - 功能: 这个指令为
location指定一个路径,它类似于root指令但是$document_root没有改变,只是请求响应使用了别名目录的文件。
小结
- 使用
alias时,目录名后面不要忘记加/。 alias只能位于location中。alias使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
参考
- http://nginx.org/en/docs/http/ngx_http_core_module.html#root
- http://nginx.org/en/docs/http/ngx_http_core_module.html#alias