关于 nginx 中 location 下的 alias 配置的问题?

如果配置是

server {
    listen 8002;
    location /about/ {
      alias html;
      index index.html;
    }
  }

访问 http://localhost:8002/about/ 会返回 403 禁止

server {
    listen 8002;
    location /about/ {
      alias html/;
      index index.html;
    }
  }

访问 http://localhost:8002/about/ 会返回 html 目录下的 index.html 文件,这是符合预期的

server {
    listen 8002;
    location ~ /about/ {
      alias html/;
      index index.html;
    }
  }

访问 http://localhost:8002/about/ 会不断进行重定向生成 http://localhost:8002/about/index.html/index.html/...../index... 直到长度超过限制而访问出错。

为什么会出现第一和第三种的情况?

阅读 3.1k
2 个回答

第一种,当访问 /about 时,他会去找文件 htmlindex.html 而不是预期的 html/index.html

(很多文章都说要加上尾斜杠,实际也确实如此,但是 nginx 的官方手册中似乎没有提及。不过给出的示例里面都是有的)

第三种,按照手册上的说法,你应该使用捕获组。

If alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:

location ~ ^/users/(.+.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}

alias 的文档描述是替换一个指定的路径,这里的路径指的是nginx宿主机上的文件路径。比如:

location /i/ {
    alias /data/w3/images/;
}
# 当请求路径为 /i/top.gif 时,会返回 /data/w3/images/top.gif 这个文件

第一个例子中:请求路径会被映射成 /html/index.html, nginx 会尝试访问这个文件,由于nginx没有权限访问,所以会返回 403。

当在正则表达式中使用 alias 时,正则表达式中应该包含捕获,并且在 alias 中明确指定替换捕获。

location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;
}

第三种写法是不和规范的。

详情见 nginx alias 文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题