如何使用.htaccess文件确保存在所有三个变量

时间:2013-04-02 10:28:38

标签: .htaccess url-rewriting

在我的网站上,我向人们展示了两张定制摩托车的图像,并允许他们投票选出最喜欢的摩托车。当他们点击按钮进行投票时,我会传递赢家ID,输家ID,然后是时间。我使用ColdFusion来确定id和时间是否合适。

我的问题在于.htaccess文件。如果没有三个变量,我想将它们重定向到起始页面。

--- is a good url
http://www.flyingpiston.com/rate/ 

--- is a good url
http://www.flyingpiston.com/rate/1502/1991/2013-4-2-4-43/

--- is NOT a good url
http://www.flyingpiston.com/rate/1502/1991/

--- my current settings
RewriteRule ^rate/([0-9]+)/([0-9]+)/(.*)/ /index.cfm?section=rate&winnerid=$1&loserid=$2&time=$3 [NS,L]
RewriteRule ^rate/([0-9]+)/([0-9]+)/ /index.cfm?section=rate [NS,L]
RewriteRule ^rate/ /index.cfm?section=rate [NS,L]

--- is not doing what I think it should do
RewriteRule ^rate/([0-9]+)/([0-9]+)/ /index.cfm?section=rate [NS,L]

如果第三个变量不存在,我认为上面的行应重定向到起始页。

如何调整我的语句,以便传递三个变量或没有变量?

要查看该页面,您可以转到此处:http://www.flyingpiston.com/rate/仅使用前两个按钮进行投票。左上角的按钮传递三个变量。右上角的按钮只传递赢家和输家ID。

1 个答案:

答案 0 :(得分:1)

它会测试完整的网址,但事实上存在一些不完善之处:

这一行

RewriteRule ^rate/([0-9]+)/([0-9]+)/(.*)/ /index.cfm?section=rate&winnerid=$1&loserid=$2&time=$3 [NS,L]

匹配一个空字符串作为第三个匹配,也许您应该将其更改为

RewriteRule ^rate/([0-9]+)/([0-9]+)/(.+)/ /index.cfm?section=rate&winnerid=$1&loserid=$2&time=$3 [NS,L]

此外,这一行:

RewriteRule ^rate/([0-9]+)/([0-9]+)/ /index.cfm?section=rate [NS,L]

匹配网址的开头而非完整网址,请尝试将其更改为:

RewriteRule ^rate/([0-9]+)/([0-9]+)(/?)$ /index.cfm?section=rate [NS,L]

(也就是说,使用行占位符的$ -end匹配整个URL,并在两种情况下重写,最后使用和不使用斜杠)。 您可以测试最后一个正则表达式here