2009-11-10 6 views
8

간단한 문제이지만 간단한 인터넷 검색을하는 답변을 찾지 못하는 것 같습니다. 이 301 행을 직접하는 레일의 방법은 무엇입니까 (http://x.com/abc>http://www.x.com/abc). before_filter?www가 아닌 ​​요청을 Rails의 www url로 리디렉션

+1

를? 그것은 무엇을 당신에게 주는가? Checkout http://no-www.org/index.php –

+0

@James - www의 일반적인 사용법. 정적 콘텐츠를 제공하기 위해 두 번째 "cookieless"도메인이 필요 없도록하기 위해서입니다. – MiffTheFox

답변

17

웹 서버 (Apache, nginx 등) 구성에서이 작업을 수행하여 요청이 레일스에 전혀 영향을주지 않도록하는 것이 가장 이상적입니다.

추가하려면 다음 before_filter 당신의 ApplicationController :

class ApplicationController < ActionController::Base 
    before_filter :add_www_subdomain 

    private 
    def add_www_subdomain 
    unless /^www/.match(request.host) 
     redirect_to("#{request.protocol}x.com#{request.request_uri}", 
        :status => 301) 
    end 
    end 
end 

아파치를 사용하여 리디렉션을하고 싶지 않은 경우, 당신은이를 사용할 수 있습니다

요한의 대답이 경우, 완벽하게 정상적으로 동안
RewriteEngine on 
RewriteCond %{HTTP_HOST} !^www\.x\.com [NC] 
RewriteRule ^(.*)$ http://www.x.com/$1 [R=301,L] 
+0

위대한 답변 존. Rails> = 2.3을 사용하고 있다면 Metal을 사용하는 것이 좋습니다. :) –

+0

고마워요! 예, 금속에 대한 좋은 지적입니다. –

+0

여러분을 환영합니다! –

7

Rails> = 2.3을 사용하고 있습니다. 새 메탈을 만드는 것이 좋습니다. Rails Metals이 더 효율적이며 더 나은 성능을 제공합니다.

$ ruby script/generate metal NotWwwToWww 

다음 파일을 열고 다음 코드를 붙여 넣습니다.

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

class NotWwwToWww 
    def self.call(env) 
    if env["HTTP_HOST"] != 'www.example.org' 
     [301, {"Content-Type" => "text/html", "Location" => "www.#{env["HTTP_HOST"]}"}, ["Redirecting..."]] 
    else 
     [404, {"Content-Type" => "text/html"}, ["Not Found"]] 
    end 
    end 
end 

물론 금속을 사용자 정의 할 수 있습니다.

Apache를 사용하려는 경우 here's a few configurations.

+0

Simone, Rails 3에서 이것을 사용하는 방법에 대한 조언이 있습니까? 'www.foo.com '을'foo.com'으로 리디렉션하고 싶습니다. –

+0

Rails 3을 사용하면 훨씬 쉬운 방법입니다. 'redirect' 라우팅 방법을 사용하십시오. 메탈을 사용할 필요가 없습니다. –

3

더 나은 레일 3 방법이있다 - 당신의 routes.rb 파일에 넣고 :

constraints(subdomain: '') do 
    match "(*x)" => redirect do |params, request| 
     URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s 
    end 
    end 
+0

링크가 끊어졌습니다. – iamnotmaynard

7

경우 :

여기

이다가 불가지론 도메인 만드는 방법을

constraints(:host => "example.com") do 
    # Won't match root path without brackets around "*x". (using Rails 3.0.3) 
    match "(*x)" => redirect { |params, request| 
     URI.parse(request.url).tap { |x| x.host = "www.example.com" }.to_s 
    } 
    end 

업데이트 레일 4, 사용 -

before_filter :add_www_subdomain 

    private 
    def add_www_subdomain 
    unless /^www/.match(request.host) 
     redirect_to("#{request.protocol}www.#{request.host_with_port}",status: 301) 
    end 
    end 
+1

덕분에 내 인생 덕분에 – Kathan

+2

이 URL 경로를 폐기합니다. –

+1

예, 홈페이지로 리디렉션되므로 매우 유용하지 않습니다. – Gediminas

0

당신은 아래의 코드를 시도 할 수 있습니다 - 왜 당신이 www가 원하는거야

location/{ 
    if ($http_host ~* "^example.com"){ 
    rewrite ^(.*)$ http://www.example.com$1 redirect; 
    } 
} 
관련 문제