【问题标题】:.htaccess RewriteRule not working, need to generate a URL friendly.htaccess RewriteRule 不起作用,需要生成一个友好的 URL
【发布时间】:2013-02-16 10:08:24
【问题描述】:

我有这个动态链接:

http://www.nortedigital.mx/article.php?id=36175&t=dobla_las_manos_el_snte__avala_reforma_educativa

我需要像这样以 URL 友好的方式进行转换:

http://www.nortedigital.mx/36174/se_enriquecio_elba_en_sexenios_del_pan.html

我有这个 RewriteRule:

RewriteRule ^([^/]*)/([^/]*)\.html$ /article.php?id=$1&t=$2 [L]

但不起作用。拜托,有人可以帮帮我吗?

【问题讨论】:

  • 测试 RewriteRules 的好资源是:htaccess.madewithlove.be - 仅供将来参考! (欢迎来到!)
  • 谢谢 GordonsBeard!很有帮助。

标签: .htaccess mod-rewrite url-rewriting seo friendly-url


【解决方案1】:

您必须在 RewriteCond 中捕获查询字符串并在 RewriteRule 中使用它

RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=(\d+)&t=(.+)$
RewriteRule ^/?article\.php$ /%1/%2.html? [R,L]

这会将客户端重定向到请求,即/36174/se_enriquecio_elba_en_sexenios_del_pan.html。现在您必须提供真实页面。为此,我们添加了一条附加规则,类似于您在问题中已有的规则

RewriteRule ^/?(.+?)/(.+?)\.html$ /article.php?id=$1&t=$2 [L]

但是现在,有一个无限的重定向循环。我们通过使用环境变量来打破这一点。这是整个完整的规则集

RewriteEngine On

RewriteCond %{ENV:REDIRECT_SEO} ^$
RewriteCond %{QUERY_STRING} ^id=(\d+)&t=(.+)$
RewriteRule ^/?article\.php$ /%1/%2.html? [R,L]

RewriteRule ^/?(.+?)/(.+?)\.html$ /article.php?id=$1&t=$2 [L,E=SEO:1]

只要未设置环境变量,此规则就会按照上述方式进行重定向。并且从article.php服务真实页面,同时设置环境变量防止循环。

您也可以为此目的使用 cookie。但是,如果在客户端中禁用了 cookie,那将会中断。

【讨论】:

  • 谢谢Olaf,它现在可以工作了,但是产生这个URL:http://www.nortedigital.mx/36196/exito_de_reforma__solo_con_apoyo_de_maestros__epn.html?id=36196&t=exito_de_reforma__solo_con_apoyo_de_maestros__epn我需要从“?”中删除结束,你知道怎么做吗?
  • @lohenzoo 抱歉,没有想到,但已修复。只需在替换末尾附加一个问号?
  • 谢谢!几乎没问题!但是发送一个 404 页面。我认为这比我想象的要复杂。
  • @lohenzoo 如果你没有像/id/t.html 这样的 URL,你需要一个额外的规则来提供真实的页面。请查看更新的答案。
猜你喜欢
  • 2014-01-25
  • 2017-02-13
  • 2013-07-27
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 2015-10-13
相关资源
最近更新 更多