V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
stille
V2EX  ›  NGINX

求教 nginx 内无法使用 include 调用含有 if 的配置?

  •  
  •   stille ·
    stilleshan · 2021-06-24 17:31:52 +08:00 · 1032 次点击
    这是一个创建于 1008 天前的主题,其中的信息可能已经有所发展或是发生改变。

    分别在 docker nginx 和 yum install nginx 两个环境下测试都报错.

    在 conf.d 内创建了域名 xxx.com.conf 并在配置中使用了 if 语句,测试通过,reload 后也生效.

    但是,当在 conf.d 创建 2.conf ,将 if 语句放在这里.
    并在 xxx.com.conf 中 include conf.d/2.conf; 测试均报错

    nginx: [emerg] "if" directive is not allowed here in /etc/nginx/conf.d/2.conf:1
    nginx: configuration file /etc/nginx/nginx.conf test failed
    

    奇怪的是 使用军哥 LNMP.org 安装的环境却成功了.

    求教大神是否是什么模块需要编译安装还是说有其他配置?

    if 语句就是简单的正则过滤.

        if ($request_uri ~* "(aaa|bbb|cdf|223|sasss)") {
            return 301 https://xxxx.com$request_uri;
        }
    
    4 条回复    2021-07-03 05:15:05 +08:00
    eason1874
        1
    eason1874  
       2021-06-24 17:38:47 +08:00
    有 if 可以 include

    你的问题应该是在 nginx.conf 写了 include conf.d/*.conf;

    所以 2.conf 不仅被 xxx.com.conf 载入了,也被 nginx.conf http 载入了,而 http 段是不支持 if 的
    stille
        2
    stille  
    OP
       2021-06-24 17:42:34 +08:00
    @eason1874 噢,感谢回复,那最佳解决方案是换个目录放这个 2.conf 吧,只要不是 nginx.conf include 的到就行...然后单独给域名.conf include 到就行
    stille
        3
    stille  
    OP
       2021-06-24 17:54:51 +08:00
    @eason1874 谢谢.测试成功了...
    ryd994
        4
    ryd994  
       2021-07-03 05:15:05 +08:00
    BTW, 你这不需要 if 啊,加一个 regex location 不就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1000 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:53 · PVG 03:53 · LAX 12:53 · JFK 15:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.