Force www. in rails
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 p开发者_开发百科ermanent "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?
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_WWW
Note: The .htaccess file should be put inside the public folder of the Rails project.
If you're on a newer Rails version, an alternative to using Apaches mod_rewrite would be using the Canonical Host Rack middleware.
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
精彩评论