2009-12-16 35 views
3

我通常习惯使用.htaccess文件来强制域名使用www。 (即http://www.example.com代替http://example.com):部队www。 in rails

#Options +Indexes 
RewriteEngine on 
RewriteBase/

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

然而,这并不在Rails应用程序工作。什么是替代这个轨道?

回答

6

入住这

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

http://www.htaccesseditor.com/en.shtml#a_WWW

注摘自: .htaccess文件应该Rails项目的公共文件夹内付诸表决。

+0

问题是通过轨道客车忽略.htaccess文件。 – Chris 2009-12-16 13:00:32

+0

没有它的工作,把它放在你的Rails项目的公共文件夹内 – khelll 2009-12-16 13:04:36

+0

啊我不得不打开该域的mod_rewrite,但现在似乎工作正常。谢谢! – Chris 2009-12-16 13:36:05

1

你可以这样做与金属

./script/generate metal www_redirect 

然后在app /金属/ 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