2

If browsing web.dev/test2, it will look into /var/www/testsite/test2.local/public. All done through local proxy.

Below rewrite running perfectly for test2 only:

upstream site.local {
    server 127.0.0.1;
}
server {
    server_name web.dev;
    root   /var/www/web.dev/public;
    index  index.php;
    try_files $uri $uri/ /index.php?$args;
    location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
    }
    location /test2 {
        proxy_pass http://site.local/;
    }
}
server {
    server_name site.local;
    root /var/www/testsite/test2.local/public;
    index  index.php;
    try_files $uri $uri/ /index.php?$args;
    location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
    }
}

I have hundreds of /test3, /test4, and so on. I don't want to write individual server directive for each of them because it will be too long and tedious.

Below is what I've done so far to do wildcard:

upstream *.local {
    server 127.0.0.1;
}
server {
    server_name web.dev;
    root   /var/www/web.dev/public;
    index  index.php;
    try_files $uri $uri/ /index.php?$args;
    location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
    }
    location /(?<mytestsite>[^/]+) {
        proxy_pass http://$mytestsite.local/;
    }
}
server {
    server_name *.local;
    root /var/www/testsite/$host/public;
    index  index.php;
    try_files $uri $uri/ /index.php?$args;
    location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
    }
}

It won't work. upstream won't accept wildcard. Use regex .* on upstream also not works.

Isak Pontus
  • 47
  • 1
  • 9

1 Answers1

0

Try using a map. Something like

map $http_host $backend {
   host1 backend1;
   host2 backend2;
   default backend1;
}

upstream backend {
    server $backend.site.tld # nginx won't recognise .local unless in DNS
}

might work. I can't guarantee this as I can't test it at the moment but it's the general route for working with variables at a low level.

Updated: nginx needs to know about its backends at startup, so you define them in your upstream directive:

upstream backend {
    server server1.site.tld;
    server server2.site.tld;
    ...
}

Then set your proxy_pass from the map:

proxy_pass   $backend;
Simon Greenwood
  • 1,363
  • 9
  • 12