Nginx如何基于子域名自动为多租户网站提供对应目录静态文件服务?
Nginx多租户静态文件服务配置方案
Absolutely, Nginx is built for exactly this kind of scalable multi-tenant setup—you won’t need to touch your config file even when adding thousands of new tenants. Here’s a step-by-step breakdown and working config example:
Core Concept
We’ll use Nginx’s variable capture to extract the subdomain (your siteCode) from the incoming request, then map that directly to the corresponding directory on your server. This dynamic mapping eliminates the need for manual config edits as you add new tenants.
Config Example
# Handle all subdomain requests server { listen 80; listen [::]:80; # Use regex to capture the subdomain (siteCode) server_name ~^(?<sitecode>[a-z0-9-]+)\.domain\.com$; # Map captured siteCode to the tenant's directory root /path/to/your/tenant_root/$sitecode; # Serve static files with standard settings location / { try_files $uri $uri/ =404; # Optional: Add caching headers for static assets expires 1y; add_header Cache-Control "public, immutable"; } } # Handle the main domain (domain.com) separately server { listen 80; listen [::]:80; server_name domain.com; root /path/to/your/main_site_root; location / { try_files $uri $uri/ =404; } }
Key Details Explained
- Subdomain Capture: The
server_name ~^(?<sitecode>[a-z0-9-]+)\.domain\.com$line uses a regex to grab the part before.domain.comand stores it in the$sitecodevariable. Adjust the regex character set ([a-z0-9-]+) if yoursiteCodeallows other characters (like underscores). - Dynamic Root: The
rootdirective uses$sitecodeto point directly to the tenant’s folder—soacme.domain.comautomatically maps to/path/to/your/tenant_root/acme, andjohn.domain.com/stuff/stuff-list.htmlwill pull from/john/stuff/stuff-list.html. - Main Domain Handling: The second server block explicitly handles
domain.comwith its own root directory, as you requested. - Static File Serving: The
try_filesdirective ensures Nginx looks for the requested file before returning a 404, which aligns perfectly with your static file deployment flow.
Important Notes
- Permissions: Make sure the Nginx process user (usually
www-dataon Debian/Ubuntu,nginxon RHEL/CentOS) has read access to all tenant directories. - HTTPS: If you’re using HTTPS, you’ll need a wildcard SSL certificate (e.g.,
*.domain.com) and update thelistendirectives to443 sslwith your cert/key paths. - Edge Cases: If you have subdomains that don’t map to tenants (like
www.domain.com), add a separate server block for those or adjust the regex to exclude them.
内容的提问来源于stack exchange,提问作者Tim Hardy
相关产品推荐
相关产品推荐

