.htaccess RewriteRule not working, need to generate a URL friendly

若如初见. 提交于 2019-12-31 03:55:07

问题


I have this dynamic link:

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

and I need to convert in URL friendly like this:

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

and i have this RewriteRule:

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

but doesn't work. Please, anybody can help me?


回答1:


You must capture the query string in a RewriteCond and use that in the RewriteRule

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

This redirects the client to request i.e. /36174/se_enriquecio_elba_en_sexenios_del_pan.html. Now you must server the real page. For that, we add an additional rule, similar to the one you already have in your question

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

But now, there's an endless redirect loop. We break this by using an environment variable. Here is the whole complete ruleset

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]

This rule does the redirect as above, as long as the environment variable is not set. And it serves the real page from article.php and sets the environment variable at the same time to prevent the loop.

You can use cookies for this purpose too. But that will break, if cookies are disabled in the client.



来源:https://stackoverflow.com/questions/15165666/htaccess-rewriterule-not-working-need-to-generate-a-url-friendly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!