Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to realize pan-domain name auto-matching directory with regular expression in nginx

Shulou Source: shulou.com Published: 2022-06-02 09:58:30 09月21日 Update

What the editor wants to share with you this time is how nginx uses regular expressions to automatically match directories for pan-domain names. The article is rich in content. Interested friends can learn about it. I hope you can get something after reading this article.

Nginx uses regular expression to realize pan-domain name automatic matching directory

The function of virtual host can be realized with nginx, and multiple URLs can be bound.

Usually, the main domain name is written in the configuration, so if you want to add a match, you need to add it manually.

Basic writing method

The most basic way to write it is server {listen 80th serversionname www.a.com;root / html/a;. } server {listen 80th serverswimname www.b.com;root / html/b; … }

Regular writing method

After the domain name is bound, it is automatically matched to the corresponding directory. There is no need for a domain name to write the configuration.

The matching directory is: html/ domain name / secondary domain name. For example, www.baidu.com will match to the baidu.com/www directory.

Server {listen 80; # $subdomain will match above the secondary domain name # $domain will match to the first-level domain name # $tld will match to the root node name server_name ~ ^ ((?. *)\.)? (? [^.] +)\. (? [a-zA-Z] +) $; # if there is no $subdomain, jump to www if ($subdomain = ") {# set $subdomain" _ "; set $subdomain" www "; return 301$ scheme://www.$domain.$tld$request_uri } root / usr/share/nginx/html/$ {domain}. ${tld} / ${subdomain};}

Other

Nginx matching order, search for a lot of articles, I will not elaborate.

Because regular expressions have the lowest matching priority, regular expressions are matched only when nothing else is matched, so you don't have to worry about affecting other exact matches.

Most people don't have so many domain names to match, on the contrary, they want to block some malicious domain names.

However, when testing, in order not to affect the running web page, you can add an ip domain name record to the hosts and test it with a domain name that does not exist.

After reading this article about how nginx uses regular expressions to automatically match directories for pan-domain names, if you think the content of the article is good, you can share it with more people.

Tags: Domain name regular directory expression article writing second-level domain name content influence test configuration good minimum accurate no host priority interest rich content then Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft Apple Shulou Information Shulou Tech Info