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

基于通配符子域名修改网站根目录的.htaccess配置需求

通配符子域名内部路径映射解决方案

下面分两种常见服务器环境给出配置方案,实现内部路径映射(无外部重定向):

Apache 环境(.htaccess 配置)

将以下代码放在 /subdomain 目录下的 .htaccess 文件中:

RewriteEngine On

# 匹配并提取通配符子域名(如 test1、test2)
RewriteCond %{HTTP_HOST} ^([a-z0-9-]+)\.domain\.com$ [NC]
# 排除 www 子域名(不需要可删除此行)
RewriteCond %1 !^www$ [NC]
# 避免循环重写:如果请求路径未包含子域名前缀才处理
RewriteCond %{REQUEST_URI} !^/%1/ [NC]

# 根路径访问 → 映射到对应子目录根
RewriteRule ^$ %1/ [L]
# 其他路径(如 /img/test.png)→ 映射到对应子目录下的路径
RewriteRule ^(.*)$ %1/$1 [L]

配置说明:

  • 利用 mod_rewrite 提取子域名到 %1 变量,自动匹配对应目录
  • [L] 标记表示终止后续规则,避免循环
  • 所有映射仅在服务器内部完成,浏览器地址栏不会变化

Nginx 环境(server 块配置)

在你的 Nginx 虚拟主机配置中添加以下内容:

server {
    listen 443 ssl;
    server_name *.domain.com;
    # 替换为你的通配符SSL证书路径
    ssl_certificate /path/to/wildcard.crt;
    ssl_certificate_key /path/to/wildcard.key;

    root /path/to/your/subdomain;
    index index.php index.html;

    # 提取子域名到变量 $subdomain
    if ($host ~* ^([a-z0-9-]+)\.domain\.com$) {
        set $subdomain $1;
    }
    # 排除 www 子域名(不需要可删除此行)
    if ($subdomain = 'www') {
        set $subdomain '';
    }

    # 根路径访问 → 内部加载对应子目录
    location = / {
        try_files /$subdomain/ /index.php;
    }

    # 其他路径 → 内部映射到对应子目录下的路径
    location / {
        try_files /$subdomain$uri $uri /index.php;
    }

    # PHP 处理配置(根据你的PHP版本调整路径)
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

配置说明:

  • 通过正则匹配提取子域名,动态拼接路径
  • try_files 指令实现内部文件查找,无外部重定向
  • 保留原有PHP处理规则,确保子目录内的PHP文件正常执行

通用注意事项:

  • 确保服务器开启对应模块:Apache需启用 mod_rewrite,Nginx无需额外模块
  • 子目录(test1、test2)需设置正确权限,保证服务器进程可读取
  • 确认通配符SSL证书有效,支持所有子域名的HTTPS访问

内容的提问来源于stack exchange,提问作者John Ramon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:07:30