nginx location 的匹配优先级与 alias 配置不生效的“骗局”(Was Re: nginx 变量)

509 views
Skip to first unread message

agentzh

unread,
May 22, 2012, 3:36:26 AM5/22/12
to wei deng, openresty
2012/5/22 wei deng <deng...@gmail.com>
>
> 最近一直在学习nginx 在网上看过您的教程,真心想跟您学习,能留个Q或MSN么

我现在已经尽量避免使用 IM 了 :) 欢迎加入 openresty 邮件组和我们交流 nginx 或者 openresty 相关的问题:

https://groups.google.com/group/openresty

> 最近有遇到问题 关于nginx alias
>
> server {
> listen 80;
> server_name domain.com *.domain;
> root /data/test/web;
>
> location ~ \.(js|css|png|jpg|gif|ico|html)$ {
> log_not_found off;
> }
>
> location /sf/ {
> alias /data/test/share/;
> }
>
> curl "http://www.domain.com/sf/t1.html"
> 通过curl访问实际访问的是root 指令下的sf/t1.html文件, 也就是这里配置的alias失效了。 请问,这个配置如何改进哈。

如果你启用 nginx 调试日志(我的 nginx
教程中有介绍:http://agentzh.org/misc/nginx/agentzh-nginx-tutorials-zhcn.html
),在你请求 /sf/t1.html 这个位置的时候,会看到 nginx.conf 中有类似下面这一行:

2012/05/22 15:30:33 [debug] 75979#0: *1 using configuration
"\.(js|css|png|jpg|gif|ico|html)$"

即这个请求匹配的是 location ~ \.(js|css|png|jpg|gif|ico|html)$ 这个配置块,而不是你期望的
location /sf/. 这是很容易理解的,毕竟前者的优先级要高于后者(这和书写顺序无关,正则模式的匹配优先级本来就要高于前缀模式)。而一个请求一个时间只能和一个
location 配置块相关联(除非通过内部跳转方式强制重新匹配 location 块)。

解决的办法是修正你的那个正则 location,避免歧义。比如,当你去除那个 location ~
\.(js|css|png|jpg|gif|ico|html)$ 之后,你的 location /sf/ 就可以顺利匹配请求 GET
/sf/t1.html 了。

Regards,
-agentzh

P.S. 同时抄送给 openresty 邮件组:https://groups.google.com/group/openresty

Reply all
Reply to author
Forward
0 new messages