Nginx之location的匹配模式和代理

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值