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

如何通过.htaccess实现URL掩码,使特定页面显示在子域名下

实现特定页面显示在子域名下的方案

嘿,我来帮你搞定这个需求!你想要让id=12的页面在mynewsubdomain.example.com子域名下展示,其他页面保留主域名,同时还要处理子域名直接访问的重定向,下面分两种主流服务器给你具体配置:

Apache 配置方案

首先确保你的Apache服务器已经开启了mod_rewrite模块,然后在主域名根目录的.htaccess文件里添加以下规则:

# 主域名下id=12的页面,重定向到子域名
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{QUERY_STRING} ^id=12$ [NC]
RewriteRule ^myuglyurl\.php$ http://mynewsubdomain.example.com/myuglyurl.php?id=12 [R=301,L]

# 子域名下非id=12的请求,重定向回主域名(或者你指定的特定页面)
RewriteCond %{HTTP_HOST} ^mynewsubdomain\.example\.com$ [NC]
RewriteCond %{QUERY_STRING} !^id=12$ [NC]
RewriteRule ^myuglyurl\.php$ http://example.com/myuglyurl.php?%{QUERY_STRING} [R=301,L]

# 子域名直接访问(无路径)时,重定向到你指定的特定页面
RewriteCond %{HTTP_HOST} ^mynewsubdomain\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteRule ^(.*)$ http://example.com/your-specific-page.php [R=301,L]

规则说明:

  • R=301是永久重定向,如果你只是临时测试可以改成R=302
  • 把最后一条规则里的http://example.com/your-specific-page.php替换成你实际要重定向的特定页面地址
  • [NC]表示忽略大小写,确保匹配更灵活

Nginx 配置方案

在你的Nginx配置文件中,分别配置主域名和子域名的server块:

主域名server块

server {
    listen 80;
    server_name example.com;

    # 匹配id=12的请求,重定向到子域名
    location = /myuglyurl.php {
        if ($arg_id = 12) {
            return 301 http://mynewsubdomain.example.com/myuglyurl.php?id=12;
        }
        # 其他请求正常处理
        try_files $uri $uri/ =404;
    }
}

子域名server块

server {
    listen 80;
    server_name mynewsubdomain.example.com;

    # 非id=12的myuglyurl.php请求,重定向回主域名
    location = /myuglyurl.php {
        if ($arg_id != 12) {
            return 301 http://example.com/myuglyurl.php?id=$arg_id;
        }
        # id=12的请求正常处理
        try_files $uri $uri/ =404;
    }

    # 子域名直接访问时,重定向到特定页面
    location = / {
        return 301 http://example.com/your-specific-page.php;
    }
}

规则说明:

  • 同样把http://example.com/your-specific-page.php替换成你实际的特定页面地址
  • 301永久重定向可根据需求改为302临时重定向
  • Nginx的if指令在这里足够处理简单的参数匹配,复杂场景可以用map指令优化

配置完成后记得重启对应的服务器服务,让规则生效哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:05:41