.htaccess 重写传递 2 个参数的 URL


.htaccess rewriting a URL which is passing 2 parameters

假设我有一个这样的网址

testingQuiz.com/my_test_link.php?id=4&name=test

现在我需要像这样重写上面的 URL,

testingQuiz.com/4/test.html

我的问题是,我如何通过 .htaccess URL 重写来实现这一点?

像下面这样的东西也许应该有效,顺便说一句,这还没有经过全面测试,但初步测试表明它按预期进行 - 尽管也许可以改进第二种样式重定向。

/* turn on url rewriting */
RewriteEngine On
/* set the level for the rewriting, in this case the document root */
RewriteBase /
/* match 2 parameters in querystring - the first is numeric and the second is alphanumeric with certain other common charachters */
RewriteRule ^([0-9]+)/([a-zA-Z0-9_-]+)'.html$ my_test_link.php?id=$1&name=$2 [NC,L]

这应该允许您以http://www.example.com/23/skidoo.html的形式编写网址/链接,并将$_GET变量解释为:

$_GET['id'] => 23, $_GET['name'] => skidoo

如果您需要自动将用户从原始样式查询字符串重定向到新的、更好的样式 URL,您可以尝试在上述规则之后添加以下内容:

RewriteCond %{THE_REQUEST} /(?:my_test_link'.php)?'?id=([^&'s]+)&name=([^&'s]+) [NC]
RewriteRule ^ %1/%2'.html? [R=302,L,NE]

这样,如果用户输入 url http://www.example.com?id=23&name=skidoo它将重定向到http://www.example.com/23/skidoo.html