Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Automatic sub-domain creation if a folder exists

I have this folder: /home/sites/dev/ Nginx serves the content of this folder if I visit "domain.com"

But, let's say that if I create a folder inside this folder, for example "wp-test", I want nginx to serve this folder if I visit "wp-test.domain.com"

It seems like "ianc" made it work on his blog post, but I can't get it to work.

Here's my config so far for nginx:

server {
    listen  80;
    server_name www.ilundev.no;
    root /home/sites/dev;
}

server {
    listen  80;
    server_name   ~^(.*)\.ilundev\.no$;

    if (!-d /home/sites/dev/ilundev.no/public/$1) {
        rewrite . http://www.ilundev.no/ redirect;
    }

    root /home/sites/dev/$1;

}

server {
    listen 80;
    server_name ilundev.no;
    rewrite ^/(.*) http://www.ilundev.no/$1 permanent;
}
like image 397
Ole Avatar asked Aug 25 '14 20:08

Ole


1 Answers

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.

like image 106
Ole Avatar answered Oct 01 '22 06:10

Ole