Asked  7 Months ago    Answers:  5   Viewed   23 times

I have a website that doesn't seem to redirect from non-www to www.

My Apache configuration is as follows:

RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc] 

What am I missing?

 Answers

33

Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

And then you'll have another <VirtualHost> section with ServerName www.example.com for your real server configuration. Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).

Tuesday, June 1, 2021
 
huhushow
answered 7 Months ago
74

Add the following rule as the first rule:

RewriteCond %{HTTP_HOST} !^(www).
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Wednesday, March 31, 2021
 
nomie
answered 9 Months ago
21

You should have a look at the URL Rewriting Guide from the apache documentation.

The following is untested, but it should to the trick:

RewriteCond %{HTTP_HOST} ^([^.]+).blah.domain.com$
RewriteRule ^/(.*)$           http://blah.domain.com/%1/$1 [L,R] 

This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.

Sunday, June 13, 2021
 
ariel
answered 6 Months ago
63

So i found the answer from another question.

Node.js: 301 redirect non-www without express

Sorry for not searching before

app.get ('/*', function (req, res, next){
  if (!req.headers.host.match(/^www./)){
      res.writeHead (301, {'Location': 'http://mysite.com'});
  }else{ 
     return next();
  }
});
Friday, August 27, 2021
 
Rakesh
answered 3 Months ago
45

Try this:

RewriteCond %{REQUEST_URI} !.(gif|jpg|css|js|ico|png)$ [NC]
RewriteCond %{REQUEST_URI} !^/(sitemap.html|includes(/.*|))$ [NC]
RewriteRule ^ /sitemap.html [R=301,L]

Sure both RewriteCond lines can be combined into 1 but I would suggest keeping it 2 separate as this is easier to read and easy to maintain in case you want to add new extensions or new directories for exclusion in future.

Friday, November 19, 2021
 
Nitin Vijay
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share