如何优化此RewriteEngine代码?

时间:2012-10-08 21:35:33

标签: php mod-rewrite

我有服务器过载,服务器管理员说这个问题是由htaccess文件引起的

这是代码:

RewriteEngine On
RewriteBase /here/
RewriteRule ^top/?$ index.php?mode=top [QSA]
RewriteRule ^top/video/?$ index.php?mode=top&cat=vids [QSA]
RewriteRule ^top/picture/?$ /index.php?mode=top&cat=pics [QSA]

RewriteRule ^random$ index.php?mode=random [QSA]
RewriteRule ^random/video/?$ index.php?mode=random&cat=vids [QSA]
RewriteRule ^random/picture/?$ index.php?mode=random&cat=pics [QSA]

RewriteRule ^new/?$ index.php [QSA]
RewriteRule ^new/video/?$ index.php?mode=&cat=vids [QSA]
RewriteRule ^new/picture/?$ index.php?mode=&cat=pics [QSA]

RewriteRule ^video/([0-9]+)_(.*)$ item.php?cat=vids&id=$1 [QSA]
RewriteRule ^picture/([0-9]+)_(.*)$ item.php?cat=pics&id=$1 [QSA]
ErrorDocument 404 /item.php

2 个答案:

答案 0 :(得分:1)

减少rewriterules,将路由完全放入PHP并处理其中的404 -

示例:

RewriteBase /my_blog

RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f
RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d
RewriteRule ^router.php [PT]

router.php中执行var_dump($_SERVER);,以便了解所请求的网址以及您可以处理的内容。

答案 1 :(得分:1)

这会让你在中途:

RewriteEngine On
RewriteBase /here/
RewriteRule ^(top|random|new)/?$ index.php?mode=$1 [QSA]
RewriteRule ^(top|random|new)/(video|picture)/?$ index.php?mode=$1&cat=$2 [QSA]
RewriteRule ^(video|picture)/([0-9]+)_(.*)$ item.php?cat=$1&id=$2 [QSA]
ErrorDocument 404 /item.php

这不会给您带来完全相同的结果 - 您的cat将是videopicture,而不是vidspics ,所以你必须改变你的脚本才能工作。

如果你无法做到这一点,你可以使用你的这个稍微简化的版本:

RewriteEngine On
RewriteBase /here/
RewriteRule ^(top|random|new)/?$ index.php?mode=$1 [QSA]
RewriteRule ^top/video/?$ index.php?mode=top&cat=vids [QSA]
RewriteRule ^top/picture/?$ /index.php?mode=top&cat=pics [QSA]

RewriteRule ^random/video/?$ index.php?mode=random&cat=vids [QSA]
RewriteRule ^random/picture/?$ index.php?mode=random&cat=pics [QSA]

RewriteRule ^new/video/?$ index.php?mode=&cat=vids [QSA]
RewriteRule ^new/picture/?$ index.php?mode=&cat=pics [QSA]

RewriteRule ^video/([0-9]+)_(.*)$ item.php?cat=vids&id=$1 [QSA]
RewriteRule ^picture/([0-9]+)_(.*)$ item.php?cat=pics&id=$1 [QSA]
ErrorDocument 404 /item.php