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

问个关于 nginx 的 server_name 的问题。

  •  1
     
  •   LeungJZ ·
    JZLeung · 2018-08-25 21:26:05 +08:00 · 2732 次点击
    这是一个创建于 2042 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在想匹配一堆 co-{hash}.test.com。请问如何写 server_name 的正则?

    需要将匹配到的 hash 重定向到 demo.test.com/hash/(这里在 location 重写一下就可以了吧?);或者将 root 目录指向 /home/enterprise/$hash

    现在的问题就是,匹配不到 co-{hash}.test.com 这个域名中的 hash 值。

    附上 server 的 conf:

    server {
        listen       80;
        server_name   ~^co-(?<hash>.+)?\.test\.com$;
        #root /home/enterprise/;
        root  /home/enterprise/$hash;
    
        access_log  logs/enterprise.access.log;
    
        location ~ \.(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {
            expires 30d;
       }
    
    
        error_page  404              /404.html;
    
        location ~ \.php$ {
            deny  all;
        }
        
        location ~ /\.ht {
            deny  all;
        }
    }
    

    百度 / Google 出来的全都是官网的 server_name 的配置,一字不差的翻译过来。

    第 1 条附言  ·  2018-08-26 22:49:41 +08:00

    好了,结贴。 只需要这么写就可以了。

    server_name     ~^co-(?<name>.+).test.com$;
    root  html/enterprise/$name;
    

    $name 就是匹配到的参数。

    官网上的 ~^(?<user>.+)\.example\.net$; 是不行的,不需要 \.

    alex8
        1
    alex8  
       2018-08-26 09:27:31 +08:00 via iPhone
    ~^后面要有空格
    LeungJZ
        2
    LeungJZ  
    OP
       2018-08-26 11:25:48 +08:00 via Android
    @sunweiqiang8 要有空格?官方的貌似也没有。
    msg7086
        3
    msg7086  
       2018-08-26 18:26:53 +08:00
    先来缩小一下范围:

    你说的匹配不到,是说没法跑进这个 server block 内部,还是说$hash 为空?

    如果$hash 为空,有没有试过在 location block 内部读取$hash 的值?
    LeungJZ
        4
    LeungJZ  
    OP
       2018-08-26 18:54:21 +08:00 via Android
    @msg7086 跑不到内部。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5287 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:17 · PVG 15:17 · LAX 00:17 · JFK 03:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.