Linux – Using Nginx to serve Multi-tenant app with HTTPS

httpslets-encryptlinuxnginxPROXY

We have a multi-tenant application (dotnet core + Angular), the main website url for https://example.com, The customers URLs are (http://cust1.example.com, http://cust2.example.com,…...)

If the customer need to use his own domain, he just need to redirect his to domain to our server, for example: Customer 1 has his own domain: customer1.com, so he will go to domain setting and edit the DNS setting to refer to our server IP record @ = X.X.X.X (Our server IP) record CNAME www = cust1.example.com Then he can open his app using his domain (http://customer1.com) instead of using (http://cust1.example.com)

No, we go to the next step and use HTTPS, I have created a wildcard certificate with LetsEncrypt using certbot: sudo certbot –server https://acme-v02.api.letsencrypt.org/directory -d *.example.com –manual –preferred-challenges dns-01 certonly

Now, the application works as HTTPS if you visit it with (https://cust1.example.com) and working fine,

But the problem is, how to serve the HTTPS with different domain names, let's say that I want to visit https://customer1.com, it's obviously cant serve because there is no certificate in the server with this domain name.

We need an automatic way to create a certificates to the new domains without create a new block in the nginx config file, because maybe will be 100000 customers, so it's impossible to do it manually.

Here is my Nginx config file now

server {
    listen 80 default_server;
    return 301 https://$host$request_uri;
}
server {
    listen 443 ssl default_server;
    server_name example.com *.example.com;

     access_log /var/log/nginx/example.com.access.log;
     error_log /var/log/nginx/example.com.error.log;
     ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
 proxy_pass http://localhost:5000;
 proxy_http_version 1.1;
 proxy_set_header Upgrade $http_upgrade;
 proxy_set_header Connection keep-alive;
 proxy_set_header Host $host;
 proxy_cache_bypass $http_upgrade;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
    }

}

I tried to use Lua with nginx, but I didn't find the way to do that,

Anyone can suggest a solution fir this issue?

Best Answer

I hope you can find solution with below mentioned vhost file.

server {
    server_name *.myapp.io;
}

server {
    server_name ~^(?<account>.+)\.myapp\.io$;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_param ACCOUNT $account; # $_SERVER['ACCOUNT']
    }
}

server {
    server_name ~^(?<account>.+)\.myapp\.io$;

    root /var/www/$account;

    access_log /var/log/nginx/$account-access.log;
    error_log  /var/log/nginx/$account-error.log;
}
Related Topic