[英]Redirect non-www requests to www URLs in Ruby on Rails
這是一個簡單的問題,但我似乎無法通過快速谷歌搜索找到答案。
Ruby on Rails 直接執行此 301 的方式是什么( http://x.com/abc > http://www.x.com/abc )。 一個before_filter
?
理想情況下,您應該在您的 Web 服務器(Apache、nginx 等)配置中執行此操作,這樣請求甚至根本不會觸及 Rails。
將以下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
如果您確實想使用 Apache 進行重定向,則可以使用以下命令:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.x\.com [NC]
RewriteRule ^(.*)$ http://www.x.com/$1 [R=301,L]
對於 rails 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
雖然約翰的回答非常好,但如果您使用的是 Rails >= 2.3,我建議您創建一個新的 Metal。 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
當然,您可以進一步自定義 Metal。
如果你想使用Apache, 這里有一些配置。
有一個更好的 Rails 3 方式 - 把它放在你的routes.rb
文件中:
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
更新
以下是使其與域無關的方法:
constraints(subdomain: '') do
match "(*x)" => redirect do |params, request|
URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s
end
end
另一種解決方案可能是使用rack-canonical-host gem ,它具有很多額外的靈活性。 向 config.ru 添加一行:
use Rack::CanonicalHost, 'www.example.com', if: 'example.com'
僅當主機匹配example.com 時才會重定向到www.example.com 。 github README 中有很多其他示例。
你可以試試下面的代碼——
location / {
if ($http_host ~* "^example.com"){
rewrite ^(.*)$ http://www.example.com$1 redirect;
}
}
我在嘗試實現相反的目標(www 到根域重定向)時發現了這篇文章。 所以我寫了一段代碼, 將所有頁面從 www 重定向到根域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.