2025年2月24日 星期一 甲辰(龙)年 腊月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 服务器 > Nginx

nginx中如何实现if/else

时间:02-27来源:作者:点击数:57

一直都知道nginx支持if语法,而且语法和平常的开发语言代码格式差不多:

  • # 需要注意的是:if条件判断语句是用一个等号进行相等判断
  • if ($flag = '1') {
  • return 404;
  • }

然而,今天需要在nginx中设置if/elseif条件过滤,却发现不支持else;

最后在网上找到到如下解决方案:

  • server {
  • server_name cdsy.xyz;
  • listen 80;
  • location / {
  • set $flag 0;
  • if ($host = v.cdsy.xyz) {
  • set $flag 1;
  • }
  • if ($host = f.cdsy.xyz) {
  • set $flag 2;
  • }
  • if ($flag = 0) {
  • # 没有匹配到,跳转到默认页面
  • proxy_pass https://127.0.0.1:8000;
  • }
  • if ($flag = 1) {
  • # 匹配到条件1,跳转到8001端口
  • proxy_pass https://127.0.0.1:8001;
  • }
  • if ($flag = 2) {
  • # 匹配到条件2,跳转到8002端口
  • proxy_pass https://127.0.0.1:8002;
  • }
  • }
  • }

以上代码等效于:

  • if(host == v.cdsy.xyz) {
  • 跳转https://127.0.0.1:8001
  • } else if(host == f.cdsy.xyz) {
  • 跳转https://127.0.0.1:8002
  • } else {
  • 跳转https://127.0.0.1:8000
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门