首页 > nginx 匹配首页怪异问题

nginx 匹配首页怪异问题

upstream backend {
    server 192.168.0.100:80;
    server 192.168.0.100:81;
}
server {
    listen 80;
    server_name www.abc.com abc.com;
    root  /opt/wwwroot/abc.com/;

    location / {
        proxy_pass https://backend;
        proxy_set_header   Host   $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_hide_header X-Powered-By;
    }

    location = / { 
        index index.html index.htm index.php;
    }
}

我想当用户访问www.abc.com/ 的时候不走proxy_pass . 直接访问本地的/opt/wwwroot/abc.com/index.html 页面,其余的请求都走proxy_pass
搞了半天搞不定,有些怪异,求大神们帮忙看看。。


这是nginx的默认location匹配规则导致的,nginx的location匹配的是相对URI,nginx的location匹配规则如下:

  1. 首先匹配“=”,也就是所谓的精确匹配
  2. 其次,匹配正则表达式,例如"~"或者"^~"
  3. 再其次,按照配置文件的顺序进行匹配
  4. 最后,交给/进行通用匹配

理解了nginx的location匹配规则,你的情况就很容易解释了,www.abc.com/的相对URI时/,首先时精确匹配location = / ,其他例如www.abc.com/adf的相对URI是/adf,根据你的location匹配规则交给了通用匹配

想解决这个问题将index放在通用匹配里就行了,单独写一个location = / {}从你的需求来看没有什么作用


下面的location不需要的,直接在上面 index index.html; 这样就行了


把两个location换下位置。。。


location = / {
  rewrite / /index.html break;
  root /usr/share/nginx/html;
  index index.html;
}
【热门文章】
【热门文章】