【问题标题】:How to use htaccess url rewrite for removing a querystring如何使用 htaccess url rewrite 删除查询字符串
【发布时间】:2017-01-06 13:46:44
【问题描述】:

我有一个网站可以重定向到带有查询字符串的页面。我需要使该网址对 SEO 友好。网址是

http://www.tasteofkochi.com/dine-detail.php?a=51-fort-kochi-mattanchery

我需要它看起来像

http://www.tasteofkochi.com/dine-detail/51-fort-kochi-mattanchery

我想删除 '.php' 扩展名,然后将 '?a=' 替换为 '/'

谁能告诉我如何实现它。

【问题讨论】:

  • .htaccess 重写服务器端,例如,您将 https://example.com/foo/bar 放在网络浏览器地址栏中,网络服务器将其发送到 https://example.com/index.php?foo=bar 。您可以执行从 https://example.com/index.php?foo=barhttps://example.com/foo/bar 的 301 重定向 - 类似于 RewriteCond %{QUERY_STRING} a=70$ 后跟 RewriteRule (.*) /dine-detail/? [R=301,L](以执行重定向。

标签: php apache .htaccess mod-rewrite


【解决方案1】:

当然,你可以这样做:

RewriteEngine on

# 301 redirect any requests for /dine-detail.php?a=xx to /dine-detail/xx
RewriteCond %{QUERY_STRING} (?:^|&)a=([^&]+)(?:&|$)
RewriteRule ^dine-detail\.php$ /dine-detail/%1? [R=301,END]

# Rewrite requests for /dine-detail/xx to /dine-detail.php?a=xx
RewriteRule ^dine-detail/(.+)$ dine-detail.php?a=$1 [QSA,END]

这有两件事。对旧样式 URL 的任何请求都会 301 重定向到新 URL(外部 301 重定向,因此浏览器中的 URL 会发生变化),而新 URL 会被静默重写以使用脚本,就好像它们从未更改过一样(内部重写)。

它只适用于 dine-detail.php 页面。如果您希望它更通用并适用于其他页面,请告诉我,但这是您要求的。

您可以在新的 /dine-detail/xxx URL 上使用查询字符串,并且 a= 将被附加到它们。旧 URL 上的任何查询字符串参数(a=xxx 除外)都将被重定向丢弃。

它需要进入您网站根目录的.htaccess 文件或主服务器配置中网站文档根目录的<Directory> 块。

【讨论】:

  • 我相信这会导致内部重写循环,因为两个规则具有相同的模式。
  • 我知道它看起来是这样,但这就是 [L] 标志的用途,它代表“LAST”,因此一旦其中一个匹配,就不会再处理更多规则。 More info here.
  • 不,L 不会做你认为的那样。在 htaccess 上下文中,它的工作方式类似于 continue 循环。
  • 谢谢。在那种情况下,它可以用 END 代替,但 L 以前为我工作过。认为你是对的,但那是在服务器配置中,现在只是测试。
  • 是的,正如你所说,L 在 htaccess 中不好用。它适用于 END。谢谢。更新指令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多