Rootop 服务器运维与web架构

nginx中if和location优先级问题

问题:nginx要实现代理wss访问(websocket secure),但是配置以后测试提示404,配置如下:
# nginx配置

server
{
	#略过部分配置

    location /wss {
		proxy_pass http://127.0.0.1:8202;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "Upgrade";
		proxy_set_header X-Real-IP $remote_addr;
		proxy_read_timeout  84000;
	}
	
	if (!-e $request_filename) {
		rewrite ^/(.*)$ /index.php/$1 last;
		break;
	}
}

提示404也就是未匹配到location,发现是下面if段的问题。
把配置改为如下:

server
{
	#略过部分配置
	
    location / {
      if (!-e $request_filename) {
          rewrite ^/(.*)$ /index.php/$1 last;
          break;
      }
    }
	
    location /wss {
		proxy_pass http://127.0.0.1:8202;
		proxy_http_version 1.1;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "Upgrade";
		proxy_set_header X-Real-IP $remote_addr;
		proxy_read_timeout  84000;
	}
	
}

这样才实现访问到location /wss {} 段。
查资料说if相当于在内部实现一个location,如果匹配了,只会执行这个内部的动作。
换句话说,if和location同级的时候,if优先级高于location。
所以把if(){}放到location / {}中后问题解决。

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/4559.html

作者:Venus

服务器运维与性能优化

评论已关闭。