0

Previously my host provider gave an option of setting up rewrite rules in apache configuration files. At that time below rule worked fine.

# Non WWW URLs to WWW URLs
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]

Right now I am moving all these rules to .htaccess and in every redirect, it adds the document root like /var/www/sites... in URL.

Why is this behaving differently ?

3
  • Why don't you use the simpler Redirect directive, specified once, in the main web server configuration? Ideally .htaccess files should be reserved for directory specific configuration, not server specific. Oct 1, 2013 at 8:52
  • @Colin'tHart My host provider has revoked web server configuration (you meant apache configuration in virtual host right ? ) citing security reasons, so am forced to shift to .htaccess
    – GoodSp33d
    Oct 1, 2013 at 10:39
  • That's a good reason to stay with .htaccess Checking the documentation I see that Redirect should work in .htaccess files too httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect Oct 1, 2013 at 11:24

3 Answers 3

0

mod_rewrite behaves differently inside an htaccess files. In the docs it makes note of the fact.

If you wish to match against the full URL-path in a per-directory (htaccess) RewriteRule, use the %{REQUEST_URI} variable in a RewriteCond.
0

You very likely need to specify a RewriteBase if you are using mod_rewrite from an .htaccess file.

1
  • Yes its set in beginning itself as RewriteBase /
    – GoodSp33d
    Oct 1, 2013 at 8:28
0

Richard Salts has a hint of what you need. I just solved this problem for myself.

The Apache documentation is a little bit ambiguous about what they mean here:

If you wish to match against the full URL-path in a per-directory (htaccess) RewriteRule, use the %{REQUEST_URI} variable in a RewriteCond.

They mean use a RewriteCond to do your matching before your RewriteRule, and then use the placeholder variable from the RewriteCond in your RewriteRule's substitution (Substitution refers to what the URL will be rewritten to; it's the second parameter in a RewriteRule directive).

To reference a placeholder from the last RewriteCond executed before a RewriteRule, use %N instead of $N. Here's your solution:

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

Not the answer you're looking for? Browse other questions tagged .