Setting up a custom domain on Heroku with CNAME redirection for www subdomain

I use Heroku and added a couple of custom domains for my application, i.e. myapp.com and www.myapp.com .

My GoDaddy DNS has three A records for "@" pointing to three separate Heroku IPs, and a CNAME for the www subdomain, which points to proxy.heroku.com .

I want to redirect any traffic from www.myapp.com to myapp.com . I tried setting CNAME to "@", but it still remains in the same domain. Is there a way to force this redirect at the DNS level?

+7
ruby-on-rails dns heroku cname
source share
3 answers

CNAME is not a redirect, but a canonical name for your domain. This means that it behaves exactly the same as the domain it points to (myapp.com in your case). Your browser receives the same IP address as myapp.com and sends it a request.

Redirects run at the HTTP level or higher. You can do this, for example, in your application or create another simple application for this.

Here is a simple example for redirecting directly to your application:

 # in your ApplicationController before_filter :strip_www def strip_www if request.env["HTTP_HOST"] == "www.myapp.com" redirect_to "http://myapp.com/" end end 

Or you could use rails metal, which would do the same, but much faster:

 # app/metal/hostname_redirector.rb class HostnameRedirector def self.call(env) if env["HTTP_HOST"] == "www.myapp.com" [301, {"Location" => "http://myapp.com/"}, ["Found"]] else [404, {"Content-Type" => "text/html"}, ["Not Found"]] end end end 

You can also use Regex to match all requests from www. before the host name.

+8
source share

And here is the solution for node.js

 $ heroku config:set APP_HOST=yourdomain.com app.configure('production', function() { // keep this relative to other middleware, eg after auth but before // express.static() app.get('*', function(req, res, next) { if (req.headers.host != process.env.APP_HOST) { res.redirect('http://' + process.env.APP_HOST + req.url, 301) } else { next() } }) app.use(express.static(path.join(application_root, 'static'))) }) 

It will also redirect domain.herokuapp.com to yourdomain.com, preventing search engines from indexing duplicate content.

+1
source share

You can also do this quite easily in any Rack application by installing the rack-canonical-host stone and placing it in your Rack configuration file:

 require 'rack-canonical-host' use Rack::CanonicalHost, 'myapp.com' 
0
source share

All Articles