HTACCESS:如何简化我的重写规则


HTACCESS : how to simplify my RewriteRule

我正在处理我网站的照片部分,当选择要查看的图片时,您可以使用不同的导航菜单来获取您想要的内容(最新、趋势、朋友、收藏夹等),还可以按日期、评级、浏览量等对图片进行排序。

哦,还有一个分页系统,我用它一页只显示几张图片。

现在我有这个:

RewriteRule ^photo$ photo.php?tab=latest
RewriteRule ^photo/trending$ photo.php?tab=trending
RewriteRule ^photo/friends$ photo.php?tab=friends
RewriteRule ^photo/favorite$ photo.php?tab=favorite
RewriteRule ^photo/page:([0-9]+)/$ photo.php?tab=latest&page=$1
RewriteRule ^photo/trending/page:([0-9]+)/$ photo.php?tab=trending&page=$1
RewriteRule ^photo/friends/page:([0-9]+)/$ photo.php?tab=friends&page=$1
RewriteRule ^photo/favorite/page:([0-9]+)/$ photo.php?tab=favorite&page=$1
RewriteRule ^photo/sort:([A-Za-z0-9]+)/page:([0-9]+)/$ photo.php?tab=latest&page=$2&sort=$1
RewriteRule ^photo/trending/sort:([A-Za-z0-9]+)/page:([0-9]+)/$ photo.php?tab=trending&page=$2&sort=$1
And so on

我想知道有没有可能让.htaccess文件检测到任何page:([0-9]+),然后自动向php文件发送一个带有页码的变量。这将是非常有帮助的,因为我还有一篇文章,视频和论坛部分,将具有相同的功能。

尝试替换为:

# Extract out the "page" and "sort" parts of the URI, and append them to the query string
RewriteRule (.*)/page:([0-9]+)/(.*) /$1/$3?page=$2 [L,QSA]
RewriteRule (.*)/sort:([A-Za-z0-9]+)/(.*) /$1/$3?sort=$2 [L,QSA]
# Proceed with the regular routing
RewriteRule ^photo/?$ photo.php?tab=latest  [L,QSA]
RewriteRule ^photo/trending/?$ photo.php?tab=trending [L,QSA]
RewriteRule ^photo/friends/?$ photo.php?tab=friends [L,QSA]
RewriteRule ^photo/favorite/?$ photo.php?tab=favorite [L,QSA]

这里的关键是在任何地方都使用QSA标志,这样,当查询字符串组合在一起时,就可以根据需要添加新的位。另一件事是常规路由部分,我在正则表达式匹配的末尾添加了/?,因为在页面/排序处理中,可能会出现尾部斜杠。