title: NGINX Configuration for Multi-Tenant Application with Domain Mapping
body: <p>I'm developing a multi-tenant application with Laravel (PHP) as backend; and using NGINX as my web-server.</p>
  <p>Aim: To allow each of my tenant to have their own subdomains; and also let them map their own subdomains or root domains using CNAME. Each subdomain / root domain will be served via HTTPS.</p>
  <p>My NGINX Configuration -</p>
  <pre><code>server {
      listen 80;
      listen [::]:80;
      server_name *.domain.com;
      return 301 https://$host$request_uri;
  }
  
  server {
          listen 443 ssl;
  
          root /var/www/html/public;
  
          add_header X-Frame-Options &quot;SAMEORIGIN&quot;;
          add_header X-XSS-Protection &quot;1; mode=block&quot;;
          add_header X-Content-Type-Options &quot;nosniff&quot;;
  
          # Add index.php to the list if you are using PHP
          index index.php index.html index.htm index.nginx-debian.html;
  
          charset utf-8;
  
          server_name *.domain.com;
  
      ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;   
  
          location / {
                  # First attempt to serve request as file, then
                  # as directory, then fall back to displaying a 404.
                  try_files $uri $uri/ /index.php?$query_string;
          }
  
          location ~ \.php$ {
                  fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
                  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                  include fastcgi_params;
          }
  
          location ~ /\.(?!well-known).* {
                  deny all;
          }
  }
  </code></pre>
  <p>Above configuration works for any <code>&lt;subdomain&gt;.domain.com</code> that my users can create from the web UI of my application.</p>
  <p>My aim is to let them point their CNAME records to their respective <code>&lt;subdomain&gt;.domain.com</code> and have a complete white-label solution that runs on their own domain.</p>
  <p>Would really appreciate some guidance.</p>