views:

105

answers:

4

My rails app seems to break when it answers on www.example.com, it previously was working fine with just example.com...however I've moved servers recently and would like to know the best way to redirect all www.example.com requests to go to http://example.com/.../

thanks.

A: 

Hi,

It depends on your server setup and there are different ways. You can just cname www in DNS to the root domain, for one way. If you are running Rails behind Apache then you can do it in Apache with mod_rewrite. If you are taking network requests straight into Rails with eg, mongrel (or webbrick) then you may have to configure those servers, or might have to use Rails routes ?

Hope that helps,

adricnet

adric
A: 

According to the Apache's name-based virtual host documentation the first virtual host is the default host. I use this to make the first entry a catch-all that redirects every "undefined" request to the main site:

# Default catch-all
<VirtualHost *:80>
    # Note the lack of a ServerName
    RewriteRule ^(.*)$ http://www.example.com$1 [redirect=permanent]
</VirtualHost>

# Site 1 - www.example.com
<VirtualHost *:80>
    ServerName www.example.com

  [ the rest of the site config ]

</VirtualHost>

For extra credit you can set up a wildcard DNS entry so that every undefined host (e.g. asdfasdfasdfas.example.com) gets redirected to www.example.com.

Gerald Combs
+1  A: 

This should do the trick, assuming that you have mod_rewrite enabled

    RewriteEngine on

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

You might not want to hear it but I suggest fixing what breaks instead. You've hard coded your domain somewhere in your app, probably in your routing but it is not possible to tell without the specifics of the error(s), and you need to remove that so you, or some other maintainer, won't have to deal with it again in the future.

srboisvert