nginx配置首页和反向代理

location  ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|pdf|js|css)$ {  
    root   root;  
    index  index.html index.htm;  
}  
location / {  
                proxy_pass http://target;  
 }

nginx配置如上,浏览器输入localhost:3000为什么打开的不是root目录下的index.html,而是代理的地址,输入localhost:3000/index.html返回的也是404
需要怎样配置

阅读 4.9k
3 个回答

location 优先级官方文档

1 Directives with the = prefix that match the query exactly. If found, searching stops.
2 All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
3 Regular expressions, in order of definition in the configuration file.
4 If #3 yielded a match, that result is used. Else the match from #2 is used.

1 =前缀的指令严格匹配这个查询。如果找到,停止搜索。
2 所有剩下的常规字符串,最长的匹配。如果这个匹配使用^~前缀,搜索停止。
3 正则表达式,在配置文件中定义的顺序。
4 如果第3条规则产生匹配的话,结果被使用。否则,使用第2条规则的结果。

Nginx 会从上至下进行匹配,若匹配到一个 location,则执行该 location 逻辑,忽略后面所有的正则 location,终止匹配;若一个正则都没匹配上,则执行之前保留的那个无符号 location,若之前没有保留,则直接返回 404

示例

location  = / {
  # 只匹配"/".
  [ configuration A ] 
}
location  / {
  # 匹配任何请求,因为所有请求都是以"/"开始
  # 但是更长字符匹配或者正则表达式匹配会优先匹配
  [ configuration B ] 
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location
  [ configuration C ] 
}
location ~* .(gif|jpg|jpeg)$ {
  # 匹配以 gif, jpg, or jpeg结尾的请求. 
  # 但是所有 /images/ 目录的请求将由 [Configuration C]处理.   
  [ configuration D ] 
}

匹配到根路径后,会将请求转交给你指定的代理。所以不会使用你指定的index。
无法打开index.html,可能是你设置的root路径有问题,你是为了保密所以没有把路径贴上来吗?还是说你配置中也是这样?
正确的root参数应该是一个绝对路径, 比如root /var/www/;

声明一点.location匹配会匹配多个.我们用你访问的路径localhost:3000/index.html,再来查看你的代码.
很明显./index.html是满足第一个location的.第一个location匹配完成过后.就改变了root指令和index指令.

location  ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|pdf|js|css)$ {  
    root   root;  
    index  index.html index.htm;  
}  

当匹配完第一个过后,你并没有终止location.所以就会往下执行.就会遇到如下

location / {  
    proxy_pass http://target;  
}

匹配到所有了.就会进行一次反向代理.代理到target所指的上游upstream.这个就看你有没有设置.既然理解了匹配原理.就容易修改了.如果不想匹配两个location,则在第一个location的指令中加上break指令.如果是因为upstream没有index.html.那就修改成正确的代理.

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