如何在htaccess中将这个双变量url重写为漂亮的url

How to re-write this double variables url in htaccess in to pretty url

提问人:smallbee 提问时间:3/14/2023 更新时间:3/14/2023 访问量:47

问:

我只想要这个网址

example.com/?cat_page_10=2 

添加到此 URL 中

example.com/cat-page/10/2.html

上面的 URL 有两个(双)可变量 10 和 2 都是可灵活/动态变量,它们会根据请求的页面而变化。

我试过这个

RewriteRule ^cat-page/([^/]*)\.html$ /?cat_page_10=$1 [L]

但结果是这样的

http://example.com/cat-page/2.html

我想要这个

example.com/cat-page/10/2.html 

因为 10 也是 url 中的动态变量,所以 iw ant 都会根据请求的 url 而变化 有人帮我解决我错误的地方吗?

.htaccess mod-rewrite url-rewriting httpd.conf friendly-url

评论

1赞 CBroe 3/14/2023
“我试过这个 [...]但结果是这样的 [...]”- 这毫无意义。您正在这里重写。这不是外部重定向,因此没有“由此产生”的外部 URL。首先,您的链接正确指向,这是您在创建 HTML 输出时需要处理的事情。cat-page/xyz.html/?cat_page_10=xyz/cat-page/10/2.html

答:

1赞 anubhava 3/14/2023 #1

您现有的模式不正确,因为它只允许一个 之后。RewriteRule//cat_page

您可以使用以下规则:

RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /\?cat_page_([\w-]+)=([\w-]+)\s [NC]
RewriteRule ^ /cat-page/%1/%2.html? [R=302,L,NE]

# internal rewrite from pretty URL to actual one
RewriteRule ^cat-page/([\w-]+)/([\w-]+)\.html$ ?cat_page_$1=$2 [L,QSA,NC]

评论

0赞 Daniel Ferradal 3/14/2023
RewriteRule 永远不会匹配查询字符串,此答案无效
0赞 anubhava 3/14/2023
这不是为了匹配查询字符串,而是为了重写为 .example.com/cat-page/10/2.htmlexample.com/?cat_page_10=2
0赞 Daniel Ferradal 3/14/2023
好吧,他的帖子说他希望查询字符串 1 进入非查询字符串 1,而不是相反。
0赞 anubhava 3/14/2023
希望你也注意到OP的规则
0赞 Daniel Ferradal 3/14/2023 #2

查询字符串(? 字符后面的所有内容)永远不会与 RewriteRule 匹配,您需要 RewriteCond 来检查查询字符串

我认为你可以用这样简单的东西,这取决于这些变量是否总是数字或其他东西。

RewriteCond %{QUERY_STRING} ^cat_page_(\d+)=(\d+)$
RewriteRule ^ /cat-page/%1/%2.html [R,L]

PS:对不起,我没有及时 #httpd 帮忙。