# 智能子域名路径跳转方案

完全可以！这是一个非常聪明的想法。我来为你实现这种智能的子域名路径映射。

## 1. **核心方案：Nginx 路径到子域名映射**

### 1.1 基础配置
```nginx
# /etc/nginx/conf.d/smyhub-redirect.conf
server {
    listen 80;
    listen [::]:80;
    server_name smyhub.com www.smyhub.com;
    
    # 处理特殊路径到子域名的映射
    location ~ "^/([a-zA-Z0-9_-]+)(/.*)?$" {
        set $subdomain $1;
        set $subpath $2;
        
        # 特殊处理：直接访问主域名
        if ($subdomain = "/") {
            return 301 https://shumengya.top;
        }
        
        # 将路径转换为子域名
        return 301 https://$subdomain.shumengya.top$subpath;
    }
}
```

### 1.2 增强版配置（支持多级子域名）
```nginx
server {
    listen 80;
    listen [::]:80;
    server_name smyhub.com www.smyhub.com;
    
    # 1. 主域名直接跳转（根路径）
    location = / {
        return 301 https://shumengya.top;
    }
    
    # 2. 单级子域名映射：smyhub.com/pan -> pan.shumengya.top
    location ~ "^/([a-zA-Z0-9_-]+)$" {
        return 301 https://$1.shumengya.top;
    }
    
    # 3. 多级路径映射：smyhub.com/pan/docs -> pan.shumengya.top/docs
    location ~ "^/([a-zA-Z0-9_-]+)(/.*)$" {
        return 301 https://$1.shumengya.top$2;
    }
    
    # 4. 多级子域名映射：smyhub.com/frp.big -> frp.big.shumengya.top
    location ~ "^/([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)$" {
        # 将点转换为子域名分隔符
        set $subdomain $1;
        set_by_lua_block $target_subdomain {
            local sub = ngx.var.subdomain
            -- 将路径中的点转换为子域名格式
            sub = sub:gsub("%.", ".")
            return sub .. ".shumengya.top"
        }
        return 301 https://$target_subdomain;
    }
    
    # 5. 多级子域名+路径：smyhub.com/frp.big/docs -> frp.big.shumengya.top/docs
    location ~ "^/([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)(/.*)$" {
        set $subdomain_path $1;
        set $subpath $2;
        set_by_lua_block $target_subdomain {
            local sub = ngx.var.subdomain_path
            sub = sub:gsub("%.", ".")
            return sub .. ".shumengya.top"
        }
        return 301 https://$target_subdomain$subpath;
    }
}
```

## 2. **完整智能映射配置**

```nginx
# /etc/nginx/conf.d/smyhub-smart-redirect.conf
server {
    listen 80;
    listen [::]:80;
    server_name smyhub.com www.smyhub.com;
    
    # 开启重写日志（调试用）
    # rewrite_log on;
    # error_log /var/log/nginx/smyhub-debug.log notice;
    
    # =========== 主逻辑：智能路径解析 ===========
    
    # 1. 特殊路径直接处理
    location = /favicon.ico {
        return 404;
    }
    
    location = /robots.txt {
        return 200 "User-agent: *\nAllow: /";
    }
    
    # 2. 主域名根路径 -> shumengya.top
    location = / {
        return 301 https://shumengya.top;
    }
    
    # 3. 智能路径解析（核心逻辑）
    location ~* "^/(?<subpath>[^/.]+)(?<rest>.*)$" {
        # 使用 Lua 进行更灵活的解析
        set_by_lua_block $target_url {
            local ngx_var = ngx.var
            
            -- 获取路径部分
            local full_path = ngx_var.request_uri
            local subpath = ngx_var.subpath or ""
            local rest = ngx_var.rest or ""
            
            -- 移除开头的斜杠
            subpath = subpath:gsub("^/", "")
            
            -- 如果 subpath 为空（直接访问主域名）
            if subpath == "" then
                return "https://shumengya.top"
            end
            
            -- 处理常见的特殊路径（可自定义）
            local special_paths = {
                ["admin"] = "https://admin.shumengya.top",
                ["api"] = "https://api.shumengya.top",
                ["blog"] = "https://blog.shumengya.top",
                ["docs"] = "https://docs.shumengya.top",
                ["pan"] = "https://pan.shumengya.top",
                ["mail"] = "https://mail.shumengya.top",
                ["cloud"] = "https://cloud.shumengya.top"
            }
            
            -- 检查是否是特殊路径
            if special_paths[subpath] then
                return special_paths[subpath] .. rest
            end
            
            -- 智能解析：支持多级子域名
            -- 示例：frp.big -> frp.big.shumengya.top
            local parts = {}
            for part in subpath:gmatch("[^.]+") do
                table.insert(parts, part)
            end
            
            -- 构建目标子域名
            local target_subdomain = table.concat(parts, ".")
            
            -- 返回完整 URL
            return "https://" .. target_subdomain .. ".shumengya.top" .. rest
        }
        
        # 执行 301 永久重定向
        return 301 $target_url;
    }
    
    # 4. 404 处理
    location @404 {
        return 404 "Not Found";
    }
}
```

## 3. **带缓存的优化版本**

```nginx
server {
    listen 80;
    listen [::]:80;
    server_name smyhub.com www.smyhub.com;
    
    # 添加缓存头，告诉浏览器这个重定向是永久的
    add_header Cache-Control "public, max-age=31536000, immutable";
    
    # 主逻辑：使用 rewrite 更高效
    location / {
        # 保存原始请求
        set $original_uri $request_uri;
        
        # 移除开头的斜杠
        if ($request_uri ~ "^/([^/]+)(/.*)?$") {
            set $subdomain $1;
            set $subpath $2;
        }
        
        # 处理根路径
        if ($subdomain = "") {
            return 301 https://shumengya.top;
        }
        
        # 检查子域名是否包含点（多级子域名）
        if ($subdomain ~ "\.") {
            # 多级子域名：frp.big -> frp.big.shumengya.top
            set_by_lua_block $target_host {
                local sub = ngx.var.subdomain
                -- 将路径中的点保留作为子域名分隔符
                return sub .. ".shumengya.top"
            }
        }
        
        if ($target_host) {
            return 301 https://$target_host$subpath;
        }
        
        # 单级子域名
        return 301 https://$subdomain.shumengya.top$subpath;
    }
}
```

## 4. **支持所有情况的终极配置**

```nginx
# /etc/nginx/conf.d/smyhub-ultimate.conf
server {
    listen 80;
    listen [::]:80;
    server_name smyhub.com www.smyhub.com;
    
    # Lua 模块（需要 OpenResty 或安装 lua-nginx-module）
    set_by_lua_block $target_domain {
        local uri = ngx.var.request_uri
        
        -- 默认目标
        local target = "https://shumengya.top"
        
        -- 如果不是根路径
        if uri ~= "/" then
            -- 移除开头的斜杠和查询参数
            local path = uri:match("^/([^?]*)") or ""
            
            if path ~= "" then
                -- 分割路径部分
                local parts = {}
                for part in path:gmatch("[^/]+") do
                    table.insert(parts, part)
                end
                
                if #parts > 0 then
                    -- 第一个部分是子域名
                    local first_part = parts[1]
                    
                    -- 检查是否是带点的多级子域名
                    if first_part:find("%.") then
                        -- frp.big -> frp.big.shumengya.top
                        target = "https://" .. first_part .. ".shumengya.top"
                    else
                        -- pan -> pan.shumengya.top
                        target = "https://" .. first_part .. ".shumengya.top"
                    end
                    
                    -- 添加剩余路径
                    if #parts > 1 then
                        local remaining_path = "/" .. table.concat(parts, "/", 2)
                        target = target .. remaining_path
                    end
                    
                    -- 添加查询参数
                    local query = ngx.var.args
                    if query and query ~= "" then
                        target = target .. "?" .. query
                    end
                end
            end
        end
        
        -- 特殊路径映射（可自定义）
        local special_mappings = {
            ["/dashboard"] = "https://admin.shumengya.top",
            ["/files"] = "https://pan.shumengya.top",
            ["/blog"] = "https://blog.shumengya.top",
            ["/help"] = "https://docs.shumengya.top",
            ["/mail"] = "https://mail.shumengya.top",
            ["/cloud"] = "https://cloud.shumengya.top",
            ["/frp"] = "https://frp.shumengya.top",
            ["/frp.big"] = "https://frp.big.shumengya.top",
            ["/frp/small"] = "https://frp.small.shumengya.top"
        }
        
        -- 检查特殊映射
        if special_mappings[uri] then
            target = special_mappings[uri]
        end
        
        return target
    }
    
    # 执行重定向
    return 301 $target_domain;
    
    # 可选：记录跳转日志
    access_log /var/log/nginx/smyhub-redirect.log combined;
}
```

## 5. **实际案例测试配置**

```nginx
server {
    listen 80;
    server_name smyhub.com;
    
    # 使用 rewrite 规则（高性能）
    rewrite_log on;
    
    # 具体案例映射
    location / {
        # 案例 1: smyhub.com/pan -> pan.shumengya.top
        if ($request_uri ~ "^/pan(/.*)?$") {
            rewrite ^/pan(/.*)?$ https://pan.shumengya.top$1 permanent;
        }
        
        # 案例 2: smyhub.com/frp.big -> frp.big.shumengya.top
        if ($request_uri ~ "^/frp\.big(/.*)?$") {
            rewrite ^/frp\.big(/.*)?$ https://frp.big.shumengya.top$1 permanent;
        }
        
        # 案例 3: smyhub.com/blog/article -> blog.shumengya.top/article
        if ($request_uri ~ "^/blog(/.*)?$") {
            rewrite ^/blog(/.*)?$ https://blog.shumengya.top$1 permanent;
        }
        
        # 案例 4: smyhub.com/api/v1/users -> api.shumengya.top/v1/users
        if ($request_uri ~ "^/api(/.*)?$") {
            rewrite ^/api(/.*)?$ https://api.shumengya.top$1 permanent;
        }
        
        # 案例 5: smyhub.com/docs/getting-started -> docs.shumengya.top/getting-started
        if ($request_uri ~ "^/docs(/.*)?$") {
            rewrite ^/docs(/.*)?$ https://docs.shumengya.top$1 permanent;
        }
        
        # 默认规则：通用路径->子域名映射
        if ($request_uri ~ "^/([a-zA-Z0-9_-]+)(\.[a-zA-Z0-9_-]+)?(/.*)?$") {
            set $subdomain $1;
            set $dot_part $2;
            set $path_part $3;
            
            # 构建目标域名
            if ($dot_part) {
                # 包含点的多级子域名
                set $full_subdomain $subdomain$dot_part;
                rewrite ^ https://$full_subdomain.shumengya.top$path_part permanent;
            }
            
            # 单级子域名
            rewrite ^/([a-zA-Z0-9_-]+)(/.*)?$ https://$1.shumengya.top$2 permanent;
        }
        
        # 根路径：跳转到主站
        rewrite ^/$ https://shumengya.top permanent;
        
        # 404 处理
        return 404;
    }
}
```

## 6. **部署和测试脚本**

```bash
#!/bin/bash
# deploy-smart-redirect.sh

echo "部署智能子域名跳转服务..."

# 1. 创建配置文件
sudo tee /etc/nginx/conf.d/smyhub-smart.conf > /dev/null << 'EOF'
server {
    listen 80;
    server_name smyhub.com www.smyhub.com;
    
    # 智能路径解析
    location / {
        # 获取路径的第一部分
        if ($request_uri ~ "^/([^/?#]+)([/?#].*)?$") {
            set $subdomain $1;
            set $rest $2;
        }
        
        # 根路径 -> 主站
        if ($subdomain = "") {
            return 301 https://shumengya.top;
        }
        
        # 特殊字符处理：将路径中的点转换为子域名点
        if ($subdomain ~ "\.") {
            # frp.big -> frp.big.shumengya.top
            return 301 https://$subdomain.shumengya.top$rest;
        }
        
        # 普通路径 -> 子域名
        # pan -> pan.shumengya.top
        return 301 https://$subdomain.shumengya.top$rest;
    }
}
EOF

# 2. 测试配置
sudo nginx -t

# 3. 重载配置
sudo systemctl reload nginx

# 4. 创建测试脚本
cat > test-redirects.sh << 'EOF'
#!/bin/bash
echo "测试智能跳转功能..."
echo ""

# 测试用例数组
test_cases=(
    "http://smyhub.com"
    "http://smyhub.com/"
    "http://smyhub.com/pan"
    "http://smyhub.com/pan/"
    "http://smyhub.com/pan/files"
    "http://smyhub.com/pan/files/image.jpg"
    "http://smyhub.com/frp.big"
    "http://smyhub.com/frp.big/"
    "http://smyhub.com/frp.big/config"
    "http://smyhub.com/frp.big/config/settings.json"
    "http://smyhub.com/blog"
    "http://smyhub.com/blog/article-1"
    "http://smyhub.com/api/v1/users"
    "http://smyhub.com/docs/getting-started"
    "http://smyhub.com/mail/inbox"
)

for url in "${test_cases[@]}"; do
    echo -n "测试: $url -> "
    location=$(curl -s -I "$url" 2>/dev/null | grep -i "location:" | cut -d' ' -f2- | tr -d '\r')
    echo "$location"
    sleep 0.5
done

echo ""
echo "预期结果:"
echo "  smyhub.com           -> https://shumengya.top"
echo "  smyhub.com/pan       -> https://pan.shumengya.top"
echo "  smyhub.com/frp.big   -> https://frp.big.shumengya.top"
echo "  smyhub.com/blog      -> https://blog.shumengya.top"
EOF

chmod +x test-redirects.sh

echo "部署完成！"
echo "运行测试: ./test-redirects.sh"
```

## 7. **最简配置（推荐）**

```nginx
# 最简单高效的配置
server {
    listen 80;
    server_name smyhub.com www.smyhub.com;
    
    # 核心逻辑：路径的第一部分作为子域名
    rewrite ^/([^/]+)(/.*)?$ https://$1.shumengya.top$2 permanent;
    
    # 处理根路径（上面的规则匹配不到根路径）
    location = / {
        return 301 https://shumengya.top;
    }
}
```

## 8. **处理边缘情况的配置**

```nginx
server {
    listen 80;
    server_name smyhub.com www.smyhub.com;
    
    # 0. 健康检查
    location = /health {
        return 200 "OK";
        add_header Content-Type text/plain;
    }
    
    # 1. 处理静态文件请求（避免误转）
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        # 这些应该直接访问，不跳转
        # 如果文件不存在，可以跳转到对应位置
        try_files $uri @redirect;
    }
    
    # 2. 主要跳转逻辑
    location @redirect {
        # 获取路径的第一段
        if ($request_uri ~ "^/(?<sub>[^/.]+)(?<rest>.*)$") {
            # 如果是根路径
            if ($sub = "") {
                return 301 https://shumengya.top;
            }
            
            # 构建目标URL
            set_by_lua_block $target {
                local sub = ngx.var.sub
                local rest = ngx.var.rest
                
                -- URL 解码（处理中文路径）
                sub = ngx.unescape_uri(sub)
                
                -- 保留路径中的点
                sub = sub:gsub("%.", ".")
                
                -- 构建最终URL
                return "https://" .. sub .. ".shumengya.top" .. (rest or "")
            }
            
            return 301 $target;
        }
        
        # 默认情况
        return 301 https://shumengya.top;
    }
    
    # 3. 默认位置
    location / {
        try_files