在 .htaccess 中使用查询字符串重定向 URL

Redirect URLs with query strings in .htaccess

我正在尝试将旧站点迁移到使用 concrete5 构建的新站点。旧站点使用查询字符串,我无法从 concrete5 中重定向它。

  1. 有多个类别,如何只重定向查询部分?

    • 旧URL:example.com/portfolio/category?cat=hifi
    • 新URL:example.com/projecten/hifi
  2. 此外,我有 URLs 的不同查询也需要重定向:

    • 旧URL:example.com/portfolio/post.php?s=pagename-xxx-xxx
    • 新URL:example.com/projecten/pagename-xxx-xxx

非常感谢帮助!

您需要使用 mod_rewrite 和 条件 (RewriteCond) 匹配 QUERY_STRING 服务器变量。

在您的根 .htaccess 文件 上面 任何现有 mod_rewrite 指令中尝试以下操作。

RewriteEngine On

# PART 1 : Redirect old category URLs
RewriteCond %{QUERY_STRING} ^cat=(\w+)
RewriteRule ^portfolio/category$ /projecten/%1? [R=302,L]

# PART 2 : Redirect other old URLs
RewriteCond %{QUERY_STRING} ^s=(pagename-\w{3}-\w{3})
RewriteRule ^portfolio/post\.php$ /projecten/%1? [R=302,L]

这假设 pagename-xxx-xxx 中的 xxx 是 3 个文字字符(即 a-zA-Z0-9_).

UPDATE#1: RewriteRule 替换的结尾 ? 是必要的,以便从目标中删除查询字符串。或者,在 Apache 2.4+ 上使用 QSD 标志。

当您确定它工作正常时,将 302(临时)重定向更改为 301(永久)。 301 重定向由浏览器缓存,这会使测试出现问题。

UPDATE#2: 关于 "PART 2" 中更新的 URL,请尝试以下操作:

# PART 2 : Redirect other old URLs
# To essentially remove the date prefix, eg. "YYYY-MM-DD-"
RewriteCond %{QUERY_STRING} ^s=/d{4}-/d{2}-/d{2}-(.+)
RewriteRule ^portfolio/post\.php$ /projecten/%1? [R=302,L]

^s=[0-9{4}]+-(.+?)/?[0-9{2}]+-(.+?)/?[0-9{2}]+-(.+?)/?(.*)$

这有点像 mash,但对于您要实现的目标来说看起来过于复杂?例如,为什么需要匹配 optional 斜杠(即 /?)?您的示例 URL 不包含任何斜线?

诸如 [0-9{4}]+ 之类的正则表达式模式并没有按照您的想法行事。这将匹配任何字符 0123456789{} 1 次或多次。您似乎想要做的是准确匹配 4 位数字。例如。 [0-9]{4}(与 /d{4} 相同,使用 shorthand 字符 class)。