Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 ?

share|improve this question
    
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 1 '13 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 '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 httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect –  Colin 't Hart Oct 1 '13 at 11:24

3 Answers 3

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.
share|improve this answer

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

share|improve this answer
    
Yes its set in beginning itself as RewriteBase / –  GoodSp33d Oct 1 '13 at 8:28

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]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.