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

时间:2016-10-24 20:48:28

标签: php apache .htaccess redirect concrete5

我尝试将旧网站迁移到使用concrete5构建的新网站。旧站点使用查询字符串,我无法在具体内容中重定向。

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

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

    • 旧网址:example.com/portfolio/post.php?s=pagename-xxx-xxx
    • 新网址:example.com/projecten/pagename-xxx-xxx
  3. 非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

您需要使用与RewriteCond服务器变量匹配的mod_rewrite和条件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]

这假定xxx中的pagename-xxx-xxx是3个字面字符(即。a-zA-Z0-9_

更新#1:为了从目标中删除查询字符串,必须在?替换上尾随RewriteRule。或者,在Apache 2.4 +上使用QSD标志。

如果您确定其工作正常,请将302(临时)重定向更改为301(永久)。浏览器会缓存301重定向,这会导致测试出现问题。

更新#2:关于"第2部分"中更新的网址,请尝试以下方式:

# 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 ,但对于你想要实现的目标看起来也过于复杂?例如,为什么需要匹配可选斜杠(即/?)?您的示例网址不包含任何斜杠?

[0-9{4}]+之类的正则表达式模式并不是您所做的事情。这将匹配任何字符0123456789{} 1次或更多次。你似乎要做的是恰好匹配4位数。例如。 [0-9]{4}(与/d{4}相同,使用速记字符类)。