Welcome! Log In Create A New Profile

Advanced

Wildcard subdomains based on subdirectories

Posted by itrogers 
Wildcard subdomains based on subdirectories
April 25, 2014 12:56PM
Hello All-

I have nginx installed on a VPS I use to develop websites. We develop anywhere between 10 and 20 sites at a time, each of which we do on a subdomain. Currently, I am setting up server blocks for each site, which gets repetitive and inefficient. My goal is to setup wildcard subdomains for example.com based on whatever is in the example.com subfolder for example:

If I create a folder in /var/www/example.com/ called sub1, then I would like nginx to automatically direct visitors who visit sub1.example.com to the root of that folder.

I would like this to happen for any future subfolders I create, in that the server_name would automatically be subfoldername.example.com

Does this make sense?

I have my DNS setup for wildcard domains, so I just need Nginx to take them to the correct area.
Re: Wildcard subdomains based on subdirectories
April 25, 2014 03:33PM
It's a bit of a hack, probably better done with map, but it does the job. Let it inspire you to make it better :)

____server {
______listen 80;
______server_name .mydom.com;
______access_log logs/mydom.com.access.log main;
______error_log logs/mydom.com.error.log;
______if ($host ~ "^(w{3}\.)?(.*?)\.?mydom\.com$") { set $myuri $2; }
______if ($myuri = '') { set $myuri 'www'; }
______set $myroot '/dynhosts/$myuri';
______if ($myuri = 'www') { set $myroot '/dynhostsroot/'; }
______root $myroot;
______location / {
________index index.html index.htm;
________try_files $myroot $myroot/ =404;
______}
____}
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 329
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready