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

如何配置htaccess实现带查询字符串条件的301重定向及多域名适配?

实现分场景的301重定向配置

当然可以!你要的这种分情况的301重定向,用Apache的mod_rewrite就能完美实现。我根据你的补充需求,整理了完整的配置规则,直接放到你的.htaccess文件或者Apache主配置里就行:

前提条件

确保你的Apache服务器已经启用了mod_rewrite模块,并且如果是使用.htaccess,要在对应目录的配置里设置AllowOverride All,让重写规则生效。


完整重写规则

RewriteEngine On

# --------------------------
# 1. 无查询字符串时的跳转规则
# --------------------------
# 匹配 first-domain 的所有域名变体(带/不带www、HTTP/HTTPS),且无查询字符串
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?first-domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.first-domain.com/$1 [R=301,L]

# --------------------------
# 2. 存在查询字符串时的跳转规则
# --------------------------
# 处理 first-domain 带查询字符串的情况,跳转到 another-domain 的对应子路径并保留参数
RewriteCond %{QUERY_STRING} .+
RewriteCond %{HTTP_HOST} ^(www\.)?first-domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.another-domain.com/first-domain/$1?%{QUERY_STRING} [R=301,L]

# 处理 second-domain 带查询字符串的情况,跳转到 another-domain 的对应子路径并保留参数
RewriteCond %{QUERY_STRING} .+
RewriteCond %{HTTP_HOST} ^(www\.)?second-domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.another-domain.com/second-domain/$1?%{QUERY_STRING} [R=301,L]

规则说明

  • 无查询字符串规则:

    • RewriteCond %{QUERY_STRING} ^$:精准匹配查询字符串为空的请求
    • RewriteCond %{HTTP_HOST} ^(www\.)?first-domain\.com$ [NC]:匹配first-domain.com和www.first-domain.com,[NC]表示不区分大小写
    • [R=301,L]:R=301表示永久重定向,L表示执行完这条规则后停止后续规则处理
  • 有查询字符串规则:

    • RewriteCond %{QUERY_STRING} .+:匹配存在非空查询字符串的请求
    • ?%{QUERY_STRING}:将原请求的查询参数完整保留到目标URL中
    • 针对first-domain和second-domain分别设置规则,确保跳转到another-domain下对应的子路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:32:53