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 ?

GoodSp33d
  • 101
  • 2
  • 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. – Colin 't Hart Oct 01 '13 at 08: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 01 '13 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 http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect – Colin 't Hart Oct 01 '13 at 11:24

3 Answers3

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.
Richard Salts
  • 755
  • 3
  • 17
0

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

200_success
  • 4,701
  • 1
  • 24
  • 42
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]
BStep
  • 1
  • 2