简体   繁体   中英

what's the best way to force a domain with a rails app? ex: example.com instead of www.example.com

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.

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]

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

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 (eg asdfasdfasdfas.example.com) gets redirected to www.example.com.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM