开发者

Force www. in rails

开发者 https://www.devze.com 2022-12-14 16:40 出处:网络
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):

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号