Nginx - 限制子域中的字母数

时间:2013-06-11 08:52:00

标签: nginx

我希望任何少于六个字符的子域名都能返回404 -

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

我尝试了以下内容 -

location ~ ^/[a-z0-9-_]{0,2}$
  return 404;
}

这给了我一个错误 - unknown directive "0,2}$"

这可能吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

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

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

  2. 在您$后,您应该{打开location声明的指令。

  3. 然而,最大的问题是location与子域无关 - 在location以上的阶段,您正在寻找的是server_name。请阅读文档中有关server names的更多信息。

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

    我会尝试以下内容:

    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;
        }
    }
    

    正如我所说,上述内容尚未经过测试,但应该为您提供良好的基础。您可以在文档中详细了解PCRE正则表达式nginx用户和server_names