Nginx的location配置中,root代表web根目录,一个极简版本的Web站点配置如下。
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/www;
index index.html index.htm;
}
}
按如上配置,所有子目录默认都在同一根目录下。假设站点名字是http://server
,则请求http://server/
,指向的是/usr/share/nginx/www
。请求http://server/res
,指向的是/usr/share/nginx/www/res
。
location匹配模式及顺序
- location = /url =开头表示精确匹配,只有完全匹配上才能生效。
- location ^~ /url ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
- location ~ pattern ~开头表示区分大小写的正则匹配。
- location ~* pattern ~*开头表示不区分大小写的正则匹配。
- location /url 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后,如果没有正则命中,命中最长的规则。
- location / 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default。
子目录指向另一目录
如果要把某个子目录指向另一根目录,可增加一个location配置。
location /res {
root /usr/share/nginx/hello/;
}
这样,如果请求/res
,指向的是/usr/share/nginx/hello/res
。
子目录指向另一域名
如果要把某个子目录指向另一个域名,例如CDN访问需要,可配置代理字段。
location ^~ /res/
{
proxy_pass http://www.hello.com/;
}
如上配置,如果请求http://server/res/test.html
,
会被代理成http://www.hello.com/test.html
。
而如果这样配置。
location ^~ /res/
{
proxy_pass http://www.hello.com;
}
域名后面少一个/
,如果请求http://server/res/test.html
,则会被代理到http://www.hello.com/res/test.htm
。