我总是需要RewriteCond吗?

时间:2015-04-17 18:51:52

标签: .htaccess mod-rewrite

我的.htaccess文件中有这个片段:

RewriteCond %{QUERY_STRING} id=([0-9]+)
RewriteRule ^(20\d\d)/page/([0-9]+)/$ ?yearMeasure=$1&page=$2 [L]
RewriteRule ^(20\d\d)/$ ?yearMeasure=$1 [L]
RewriteRule ^category/([A-Za-z0-9-]+)/page/([0-9]+)/$ ?category=$1&page=$2 [L]
RewriteRule ^category/([A-Za-z0-9-]+)/$ ?category=$1 [L]
RewriteRule ^(20\d\d)/([A-Za-z0-9-]+)/$ ?type=post&year=$1&title=$2 [L,QSA]

但是,当我删除第一行时,网站的行为方式仍然相同。网址仍然保持清洁。"这让我想到了我的问题; RewriteCond在这个片段中有什么重要意义?

这个RewriteCond唯一影响的RewriteRule就是:

RewriteRule ^page/([0-9]+)/$ ?page=$1 [L]

......当我试图访问/page/2/时,它没有用。

当我将它移到RewriteCond上方时如下:

RewriteRule ^page/([0-9]+)/$ ?page=$1 [L]

RewriteCond %{QUERY_STRING} id=([0-9]+)
RewriteRule ^(20\d\d)/page/([0-9]+)/$ ?yearMeasure=$1&page=$2 [L]
RewriteRule ^(20\d\d)/$ ?yearMeasure=$1 [L]
RewriteRule ^category/([A-Za-z0-9-]+)/page/([0-9]+)/$ ?category=$1&page=$2 [L]
RewriteRule ^category/([A-Za-z0-9-]+)/$ ?category=$1 [L]
RewriteRule ^(20\d\d)/([A-Za-z0-9-]+)/$ ?type=post&year=$1&title=$2 [L,QSA]

......一切恢复正常。为什么呢?

1 个答案:

答案 0 :(得分:0)

在文档中RewriteRule以这种方式定义:

RewriteRule Pattern Substitution [flags]

如果Pattern与请求的网址匹配( domain.com /path/file.cgi),则网址将替换为Substitution(重定向标头返回或者根据标志在内部更改网址)

此重写规则:

RewriteRule ^(20\d\d)/page/([0-9]+)/$ ?yearMeasure=$1&page=$2 [L]

将检查url是否与模式匹配,只有在这种情况下才会进行替换。这就是为什么这样RewriteCond无用的原因:

RewriteCond %{QUERY_STRING} id=([0-9]+)

它在RewriteRule无法捕获的情况下非常有用,例如检查主机名或文件是否存在:

RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule .? http://example.com%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  

http://www.sitepoint.com/apache-mod_rewrite-examples-2/