【发布时间】:2011-06-22 08:29:35
【问题描述】:
我正在摆弄 .htaccess 和 mod_rewrite。我的网站有两种类型的 URL,我想重写:
-
/index.php?nav=$2 -
/index.php?nav=41&intNewsId=$3-- 41 是静态的,新闻导航总是 41
我想将它们重写为:
/pagename/id/news/pagename/id
我已经编写了一段有效的代码,但是如果我添加最后一行,第二行将停止工作,我可以想象那是因为第三块中的条件也适用于第二块强>。但我不知道如何正确使用条件。 (两个块单独工作)
Options +FollowSymlinks
RewriteEngine on
# Reroute rules that end on /
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$ /$1/$2/ [R]
# Make the system understand pagename/96
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=$2
# Make the system understand news/pagename/99
RewriteRule ^(.*)\/(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=41&intNewsId=$3
我尝试了所有我能想到的方法,但我对 htaccess 中的这种正则表达式类型的键入或条件块不太熟悉。
解决方案: 我修复了自己的代码,我只是去掉了第二个 $ 所以条件不会干扰最后一个
Options +FollowSymlinks
RewriteEngine on
# Reroute rules that end on /
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$ /$1/$2/ [R]
# Make the system understand pagename/96
RewriteRule ^(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/ /index.php?nav=$2
# Make the system understand news/pagename/99
RewriteRule ^(.*)\/(.*)\/([0-9]|[1-9][0-9]|[1-9][0-9][0-9])/$ /index.php?nav=41&intNewsId=$3
感谢大家的回答!
【问题讨论】:
-
为什么这被选为题外话?
-
另外,请注意,您可以通过使用
(\d+)来避免那些[0-9]构造的笨拙,它捕获任何一位或多位数字的块。 -
Aww 谢谢你。注意我的 ([0-9]|[1-9][0-9]|[1-9][0-9][0-9]) ,之前情况更糟:D