Nginx: Automatic sub-domain creation if a folder exists Nginx: Automatic sub-domain creation if a folder exists nginx nginx

Nginx: Automatic sub-domain creation if a folder exists


I made it work!First thing first. I had an error in my config.

The line

if (!-d /home/sites/dev/ilundev.no/public/$1) {

was wrong, and should be

if (!-d /home/sites/dev/$1) {

And, I had to set up a wildcard entry to my domain, at my domain provider. The entry looked like "*.ilundev.no" and I used the "A" option - and it worked!


Updated and optimized config:

This will work as long as the DNS at your domain provider properly sets "*.dev" in a subdomain for your domain, with the "A" option - and the IP of your server.

server {    listen 80;    server_name dev.ilun.no www.dev.ilun.no;    root /home/sites/dev;}server {    listen 80;    server_name   ~^(.*)\.dev.ilun\.no$;    if (!-d /home/sites/dev/$1) {        rewrite . http://dev.ilun.no/ redirect;    }    root /home/sites/dev/$1;}

However, now I'm stuck trying to make the server run php code in such a subdomain.


server {    listen 80;    server_name ~^(?<branch>.*)\.example\.com;    root /var/www/$branch/public;       index index.html index.htm index.php;    charset utf-8;    location / {        try_files $uri $uri/ /index.php$is_args$args;    }    location = /favicon.ico { access_log off; log_not_found off; }    location = /robots.txt  { access_log off; log_not_found off; }    error_log  /var/log/nginx/$branch.example.com.error.log error;    sendfile off;    client_max_body_size 100m;    location ~ \.php$ {       try_files $uri /index.php =404;       fastcgi_pass php-fpm:9000;       fastcgi_index index.php;       fastcgi_buffers 16 16k;       fastcgi_buffer_size 32k;       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;       include fastcgi_params;    }    location ~ /\.ht {        deny all;    }}