search
HomeBackend DevelopmentPHP TutorialNginx virtual server domain name configuration method

Nginx virtual server domain name configuration method

Mar 27, 2018 pm 02:32 PM
nginxserverConfiguration

This article mainly shares with you the Nginx virtual server domain name configuration method. The virtual server name (server name) is specified through the command server_name. exist" How does Nginx handle Request? 》In the section, we talked about nginx matching the incoming Request request in two steps:

1. Select server

2. Select location

In step 1, there are actually two steps:

1). Match port

2). Match server_name

Let’s talk about how nginx specifically matches server_name.

server_name command

There are three forms of server_name:

1. Exact names

2. Wildcard (*) form

3. Regular expression form

is as follows:

server {
    listen      80;
    server_name  example.org  www.example.org;
    ...
}
server {
    listen      80;
    server_name  *.example.org;
    ...
}
server {
    listen      80;
    server_name  mail.*;
    ...
}
server {
    listen      80;
    server_name  ~^(?<user>.+)\.example\.net$;
    ...
}

The wildcard form is actually divided into Forward wildcard character and backward wildcard character (as in the second and third examples respectively), the wildcard character cannot be located in the middle of the string.


Of course, there is a situation where a host matches one or more of the above three forms at the same time. For example, if the host is www.example.com, it can match at the same time. ;

server_name *.example.com *.com www.example.com www.example.* www.* ~^(.+)\.example\.com$

server_name Yes Of the 6 command parameters, www.example.com all matches , so which one should you choose in the end? There is a certain order:


  1. ##Exact domain name match , www.example.com

  2. Starts with the wildcard *, the longest domain name , *.example.com

  3. starts with the wildcard character * ends with the longest domain name , www.example.*

  4. and finally in the form of a regular expression, as it appears in the configuration file In order, try to match in sequence, select the first matched domain name, ~^(.+)\.example\.com$


The precise domain name form is very simple. Next, we will introduce the wildcard and regular expression forms of server_name.


Wildcard character

The use of wildcard character * in server name is very strict:

can only be located at the head of the domain name or The tail cannot appear in the middle; and must be separated by ".":

*.example.com


www.example.*

The following are illegal forms:

www.*.example.org

w*.example.org


Of course, if you want to achieve the last two Regular expressions can be used to reflect the purpose. For example, the two illegal domain names above can be written like this:

~^www\..+\.example\.org$


~^w.*\.example\.org$



Another special form can match both example.org and *.example .org, this is

.example.org


正则表达式

nginx的正则表达式语法使用的是Perl语言(PCRE)的正则语法。基本形式为

server_name  ~^www\d+\.example\.net$;

这则表达式需要注意的几点


  • 必须以~开始,没有~符号的要么被视作完全匹配或者通配符匹配

  • ~和正则表达式主体之间没有空格

  • 正则表达式主体通常以^开始以$结束(虽说语法上不一定要求如此,但是从逻辑意义上强烈要求这么做)。

  • 正则表达式中,点号"."必须转义,写作"\.";正则表达式可以不用引号包住,但是,如果其中包含"{"和"}"则必须用双引号包裹

例如:

server_name  "~^(?\w\d{1,3}+)\.example\.net$";

如果不加引号,nginx便无法正确加载配置文件,并报一个错误:

directive "server_name" is not terminated by ";" in ...


正则表达式使用命名捕获组,例如:

server {
    server_name ~^(?<myname>.+)\.example\.cn$;
    root /var/www/hb/$myname;   
}


PCRE语法支持下面几种捕获语法:

?<name>
?&#39;name&#39;
?P<name>

前面两者是最新的语法,第三种是老的写法。如果nginx报下面错误:

pcre_compile() failed: unrecognized character after (?

说明,你应该将?或者?'name'改为较古老的?P写法了。


同样,使用普通捕获组也是可以的:

server {
    server_name ~^(.+)\.example\.cn$;
    root /var/www/hb/$1;  
}

当然,普通捕获组要慎用,因为很容易被后面的正则所覆盖。


其他形式

除了两面提到的几种形式,sername_name的指令参数还有可能是其他的几种形式。

如果请求Request没有Host的头部,那么如果想要匹配,可以用空字符串:

server {
    listen      80;
    server_name  example.org  www.example.org  "";
    ...
}


另外,如果在server上下文中,没有定义 server_name,那么nginx使用空字符串作为虚拟机名称。

如果使用IP而不是域名来发起请求,那么Host请求头就是一个IP,此时server_name也可以写成一个IP:

server {
    listen      80;
    server_name  example.org
                www.example.org
                ""
                192.168.1.1
                ;
    ...
}


"_"可以用来匹配所有的域名

server {
    listen      80  default_server;
    server_name  _;
    return      444;
}

其他的字符,"-"和"!@#"也是可以的。注意,匹配所有域名的不能是"*"


最佳实践

我们知道nginx是一个款高性能的web服务器,其设计充满了许多优化的技巧。在使用的时候也不例外,如果我们能对nginx的设计原理有一些了解,我们在配置时就能很好的利用这些设计,从而使得nginx的效率达到最大化。

前面提到,server_name的指令参数匹配有一定的匹配顺序,即最先匹配精确域名形式,然后匹配以通配符*开始的域名,其次匹配以通配符*结束的域名,最后是匹配正则形式。如果前面匹配到了,就会终止继续匹配。

从原理上说,这是因为,nginx会为每个监听的port分别维护精确域名,前向通配符和后项通配符的Hash表。Hash表能在nginx启动的配置阶段得到创建和优化。精确域名的Hash表首先被搜寻,如果找不到,前向通配Hash表会被接着被搜寻,如果也没有找到,那么后向通配Hash表会被搜寻。搜寻通配Hash表要比精确域名Hash表要慢,因为其是按照域名的部分来做搜寻的(比如,*.example.com,会搜寻example和com部分)。

值得注意的是:".example.org"被存在通配Hash表里面,并没有存在精确Hash表里面,因此匹配它是较慢的。

如果以上两种方式都还没有匹配上,那么最后轮到正则形式的指令上场了。正则形式的域名是按照先后顺序一个一个的去匹配的,没有存入任何Hash表,匹配到正确的就结束,因此,这是最慢的形式,没有任何“技巧”可言。

因此,最好的配置方式就是,尽可能使用精确域名,其次是通配符形式的,最后是正则形式。即便是正则形式域名,也要根据实际需要将用的最多的域名尽量前置。这样方可使得nginx的性能达到最大化。

例如:

server {
    listen      80;
    server_name  example.org  www.example.org  *.example.org;
    ...
}

这种方式要优于:

server {
    listen      80;
    server_name  .example.org;
    ...
}

长域名,多域名的情况

在某些情况下,域名会非常的长,nginx不会允许其无限长,默认最大为32。在http上下文中,你可以通过server_names_hash_bucket_size指令来设置,可选参数有32,64(2的N次方)等

例如,如果域名被定义为:"too.long.server.name.example.org",超过32字符,那么会报错:

could not build the server_names_hash,

you should increase server_names_hash_bucket_size: 32

解决方式:

http {
    server_names_hash_bucket_size  64;
    ...

在另一些情况下,server_name配置的域名又很多,nginx同样可能报错:
could not build the server_names_hash,

you should increase either server_names_hash_max_size: 512

or server_names_hash_bucket_size: 32

这种情况下,先设置server_names_hash_max_size为一个接近你域名总数的一个合理值,如果这个还不管用,那么再调大server_names_hash_bucket_size的值(例如将2^N调整到2^(N+1))

http {
    server_names_hash_max_size:600
    server_names_hash_bucket_size 32;
    ...

如果一个域名是某个监听端口下的唯一域名,那么nginx就不会建立Hash匹配表,也不会有上面介绍的那些匹配流程,然而,如果这个唯一的域名是一个捕获组正则表达式,那么nginx还是去尝试去解析正则表达式以提取这个字段。

相关推荐:

php虚拟服务器主机

The above is the detailed content of Nginx virtual server domain name configuration method. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment