重写规则组合不起作用

时间:2014-01-10 00:22:34

标签: apache mod-rewrite url-rewriting

RewriteEngine On
RewriteCond %{HTTP_HOST} !.com$  //redirect from .net and .org to .com
RewriteRule .* http://www.domain.com%{REQUEST_URI} [R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC] //Always use www.
RewriteRule ^/(.*)$ http://www.%1/$1 [R=301]
RewriteRule ^/?article-(.*)$ article.php?id=$1 [L,QSA,NC] // redirect article-x  to article.php?id=x
RewriteRule ^/?page-(.*)$ page?p=$1 [L,QSA,NC]// redirect page-x  to page.php?p=x
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L] // add the .php to every request if the file type is missing

除了添加www之外,所有规则都可以正常工作。到网址。例如http://domain.com/page-1 不会被重定向到http://www.domain.com/page-1

1 个答案:

答案 0 :(得分:1)

%1指的是前面()中使用RewriteCond捕获的模式。您尚未在RewriteCond中捕获任何模式。相反,您只需在%{HTTP_HOST}中使用RewriteRule

如果这些规则位于.htaccess中,RewriteRule将不包含前导/,因此如果您的模式有效,则永远不会匹配。移除/并匹配^(.*)$

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301]

旁注:不要忘记逃避.中的.com。它将无效,但表达并不意味着你真正想要的意思。

RewriteCond %{HTTP_HOST} !\.com$

所有重写的完整集合应如下所示(我已删除所有前导//?表达式)。我已经在我自己的系统上测试了所有这些。

RewriteEngine On
RewriteCond %{HTTP_HOST} !\.com$ [NC]
#Use a capture group here, add [L]
RewriteRule (.*) http://www.example.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

RewriteRule ^article-(.*)$ article.php?id=$1 [L,QSA,NC]
RewriteRule ^page-(.*)$ page?p=$1 [L,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]