views:

140

answers:

3

Hey,

I'm normally used to using .htaccess files to force a domain to use www. (i.e. http://www.example.com instead of http://example.com):

#Options +Indexes
RewriteEngine on
RewriteBase /

Redirect permanent "www.example.com" "http://www.example.com"
Redirect permanent "example.com" "http://www.example.com"

However this doesn't work in a rails app. What is the rails alternative to this?

+5  A: 

Check this

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(example\.com)(:80)? [NC]
RewriteRule ^(.*) http://www.example.com/$1 [R=301,L]
order deny,allow

Taken from http://www.htaccesseditor.com/en.shtml#a%5FWWW

Note: The .htaccess file should be put inside the public folder of the Rails project.

khelll
the problem is rails via passenger ignores the .htaccess file.
Chris
no it works, put it inside the public folder of your Rails project
khelll
ah I had to turn on mod_rewrite for that domain but now seems to be working correctly. Thanks!
Chris
+1  A: 

If you're on a newer Rails version, an alternative to using Apaches mod_rewrite would be using the Canonical Host Rack middleware.

Jakob S
+1  A: 

You could do this with Metal

./script/generate metal www_redirect

And then in app/metal/www_redirect.rb

# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class WwwRedirect
  def self.call(env)
    if env["SERVER_NAME"] !~ /^www\./
      [302, {"Content-Type" => "text/html", "Location" => "http://www.#{env["HTTP_HOST"]}#{env["REQUEST_PATH"]}"}, ["Redirecting..."]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end
Dan McNevin