You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.com and stores it in the $sitecode variable. Adjust the regex character set ([a-z0-9-]+) if your siteCode allows other characters (like underscores).
  • Dynamic Root: The root directive uses $sitecode to point directly to the tenant’s folder—so acme.domain.com automatically maps to /path/to/your/tenant_root/acme, and john.domain.com/stuff/stuff-list.html will pull from /john/stuff/stuff-list.html.
  • Main Domain Handling: The second server block explicitly handles domain.com with its own root directory, as you requested.
  • Static File Serving: The try_files directive 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-data on Debian/Ubuntu, nginx on 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 the listen directives to 443 ssl with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:44:56