4

How do I make it so http://domain.com 301 redirects to http://www.domain.com? I'm used to using .htaccess to ModRewrite it, but I've learned I can't do that on Heroku.

Example of .htaccess:

Options +FollowSymlinks
RewriteEngine On

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

My file structure:

- /public
--- /style
--- index.html
- config.ru

I'm just serving up the single page, and my config.ru consists of this:

use Rack::Static,
:urls => ["/style"],
:root => "public"

run lambda { |env|
[
200,
{
'Content-Type' => 'text/html',
'Cache-Control' => 'public, max-age=86400'
},
File.open('public/index.html', File::RDONLY)
]
} 
David
  • 213
  • 4
  • 10

2 Answers2

3

use rack_rewrite (gem 'rack-rewrite' in your Gemfile) and create a rack_rewrite.rb in your initializers directory with;

YourAppName::Application.config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do
  r301 %r{.*}, 'http://www.yourdomainname.com$&', :if => Proc.new {|rack_env|
    rack_env['SERVER_NAME'] != 'www.yourdomainname.com'
  }
end if Rails.env == 'production'

this says, if the servername being requested is not www.yourdomainname.com then redirect it to www.yourdomainname.com

John Beynon
  • 37,398
  • 8
  • 88
  • 97
  • Okay, I did this...but it appears to have no effect. I added /config/initializers/, then created rack_rewrite.rb with the above code (changed my domain name in obviously), and Heroku detected and installed the rack-rewrite gem. But...nothing happens when I load domain.com (i.e. it just loads, doesnt rewrite to www). – David Jan 10 '12 at 21:22
  • odd - I lifted it straight from a production app. Ah, mine was a Rails 3.1 app - take a look at the instructions at https://github.com/jtrupiano/rack-rewrite – John Beynon Jan 10 '12 at 21:26
  • I'm thinking my rack app has no idea what /config/initializers is, considering my file structure in my main post? – David Jan 10 '12 at 21:29
  • Yeah, I'd presumed it was a Rails app (my bad) the link in my last comment has instructions for the rack up method. – John Beynon Jan 10 '12 at 21:34
  • Well, I added the rewrite part to the bottom of my config.ru as suggested in the link, and now the app won't launch. http://pastebin.com/ZLCLDCct – David Jan 10 '12 at 21:50
0

You have to add a new free Custom Domain.

Julio Santos
  • 3,837
  • 2
  • 26
  • 47
  • I have both http://www. and http:// setup, both work, but that's not what I'm asking. I want to make it load www.domain.com if you go to http://domain.com – David Jan 10 '12 at 11:28