Nginx-子域中的字母数限制

Nginx-子域中的字母数限制,nginx,Nginx,我想任何少于6个字符的子域返回404- 例如,abcd.example.com应返回404,但stackoverflow.example.com应返回index.html 我试过以下方法- location ~ ^/[a-z0-9-_]{0,2}$ return 404; } 这给了我一个错误-未知指令“0,2}$” 这可能吗 提前感谢我可以在您的代码中发现几个语法错误: Nginx使用大括号{}来指定内部指令,因此当您使用{0,2}时,它试图将其作为指令读取-您需要双引号来避免这种情况

我想任何少于6个字符的子域返回404-

例如,
abcd.example.com
应返回404,但
stackoverflow.example.com
应返回index.html

我试过以下方法-

location ~ ^/[a-z0-9-_]{0,2}$
  return 404;
}
这给了我一个错误-
未知指令“0,2}$”

这可能吗


提前感谢

我可以在您的代码中发现几个语法错误:

  • Nginx使用大括号
    {
    }来指定内部指令,因此当您使用
    {0,2}
    时,它试图将其作为指令读取-您需要双引号来避免这种情况

  • $
    之后,应该有一个
    {
    来打开
    位置
    语句的指令

  • 然而,最大的问题是
    位置
    与子域无关-您要查找的是上面的
    位置
    。请阅读文档中的更多信息

    注意:这是未经测试的代码

    我会尝试以下方法:

    server {
        listen       80;
        # We require the expression in double quotes so the `{` and `}` aren't passed as directives.
        # The `\w` matches an alphanumeric character and the `{7}` matches at least 7 occurrences
        server_name  "~^\w{7}\.example\.com";
    
        location / {
            # do_stuff...;
        }
    }
    
    server {
        listen       80;
        # We require the expression in double quotes so the `{` and `}` aren't passed as directives.
        # The `\w` matches an alphanumeric character and the `{1,6}` matches no more than 6 occurrences
        server_name  "~^\w{1,6}\.example\.com";
    
        location / {
            return 404;
        }
    }
    

    正如我所说的,上面的内容未经测试,但应该会给您提供一个很好的基础。您可以在文档中阅读更多关于正则表达式nginx用户的信息。

    非常感谢。这很有效。但是,我需要翻转“服务器”块的顺序,即我必须首先放置“允许”部分(至少7个字符匹配)在“block”部分(404为6个字符或更少)之前,该死的-如此接近于正确无需尝试:-)已经更新了我的答案。干杯