jeesk
V2EX  ›  问与答

nginx 能匹配精准包含父子关系的 location 吗 ?

  •  
  •   jeesk · Oct 26, 2020 · 1499 views
  •   You need to sign in to view this topic
    This topic created in 2055 days ago, the information mentioned may be changed or developed.

    下面是两个 location,

    location ~* ^/api/(blade-.*)|(ad-[0-9a-z]*-service)/ {  
               proxy_set_header Host $host;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_buffering off;
               rewrite ^/api/(.*)$ /$1 break;
               proxy_pass http://fad_gateway;
    }
             location ~* ^/fad-ssp/api/(blade-.*)|(ad-[0-9a-z]*-service)/ {
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_buffering off;
              rewrite ^/fad-ssp/api/(.*)$ /$1 ;
               proxy_pass http://ssp_gateway;
    }
    
    1. 我需要 访问 localhost/api/ad-1-service/123 匹配到第一个 location,
    2. 我需要 访问 localhost/fad-ssp/api/ad-1-servic/123 匹配到第二个 location,

    但实际情况下是, 我访问第 2 个地址的时候, 直接被第一个 location 匹配到了, 请问有什么办法分离吗 ?

    11 replies    2020-10-26 21:06:42 +08:00
    Lax
        1
    Lax  
       Oct 26, 2020   ❤️ 1
    匹配符号用错了,换成 ^~ 试试
    jeesk
        2
    jeesk  
    OP
       Oct 26, 2020
    试了, 如果换成^~, 都不能匹配到了
    Lax
        3
    Lax  
       Oct 26, 2020
    把两条规则的先后顺序调整一下
    jeesk
        4
    jeesk  
    OP
       Oct 26, 2020
    换了, 发现所有的 /api/ 的请求都走 /dsp-ssp/api/ 的匹配规则了
    pubby
        5
    pubby  
       Oct 26, 2020 via Android
    “|”的作用你理解错了吧
    jeesk
        6
    jeesk  
    OP
       Oct 26, 2020
    @pubby 或者没毛病呀
    jeesk
        7
    jeesk  
    OP
       Oct 26, 2020
    location ~* ^((?!fad-ssp))/api/(blade-.*)|(ad-[0-9a-z]*-service)/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_buffering off;
    rewrite ^/api/(.*)$ /$1 break;
    proxy_pass http://fad_gateway;
    }
    location ~* ^/fad-ssp/api/(blade-.*)|(ad-[0-9a-z]*-service)/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_buffering off;
    rewrite ^/fad-ssp/api/(.*)$ /$1 break ;
    proxy_pass http://ssp_gateway;
    }
    pubby
        8
    pubby  
       Oct 26, 2020 via Android
    @jeesk 按你的需求应该是
    /api/(x..... | y.....)/
    bxb100
        9
    bxb100  
       Oct 26, 2020
    @pubby #8 正解
    jeesk
        10
    jeesk  
    OP
       Oct 26, 2020
    正解, 解决了, 的确是正则表达式有问题
    jeesk
        11
    jeesk  
    OP
       Oct 26, 2020
    @bxb100
    @pubby 谢谢你们 2 位.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1112 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 18:11 · PVG 02:11 · LAX 11:11 · JFK 14:11
    ♥ Do have faith in what you're doing.