nullException
nullException

Reputation: 1122

combination of rewrite rules not working

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

all the rules work fine except for adding www. to url. for example http://domain.com/page-1 doesn't get redirected to http://www.domain.com/page-1

Upvotes: 2

Views: 89

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

%1 refers to a pattern captured with () in the preceding RewriteCond. You haven't captured any patterns in RewriteCond. Instead, you can just use %{HTTP_HOST} in the RewriteRule.

If these rules reside in .htaccess, RewriteRule will not contain a leading /, and will therefore never match if your pattern does. Remove the / and match on ^(.*)$

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

Side note: don't forget to escape the . in .com. It will work unescaped, but the expression doesn't mean what you literally intend it to mean.

RewriteCond %{HTTP_HOST} !\.com$

The full set of rewrites all together should look like the following (I have removed all the leading / and /? expressions). I have tested all of this as working on my own system.

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] 

Upvotes: 1

Related Questions