rails中子域的多个robots.txt

我有一个包含多个子域的站点,我希望命名的子域robots.txt与www一个不同。

我尝试使用.htaccess,但FastCGI不看它。

所以,我试图设置路由,但似乎你不能直接重写,因为每个路由都需要一个控制器:

map.connect '/robots.txt', :controller => ?, :path => '/robots.www.txt', :conditions => { :subdomain => 'www' } map.connect '/robots.txt', :controller => ?, :path => '/robots.club.txt' 

解决这个问题的最佳方法是什么?

(我正在使用子域的request_routing插件)

实际上,您可能希望在mime_types.rb设置mime类型并在respond_to块中执行它,因此它不会将其作为'text/html'

 Mime::Type.register "text/plain", :txt 

然后,您的路线将如下所示:

 map.robots '/robots.txt', :controller => 'robots', :action => 'robots' 

对于rails3:

 match '/robots.txt' => 'robots#robots' 

和这样的控制器(把文件放在你喜欢的地方):

 class RobotsController < ApplicationController def robots subdomain = # get subdomain, escape robots = File.read(RAILS_ROOT + "/config/robots.#{subdomain}.txt") respond_to do |format| format.txt { render :text => robots, :layout => false } end end end 

冒着过度工程的风险,我甚至可能会试图缓存文件读取操作…

哦,是的,你几乎肯定要删除/移动现有的'public/robots.txt'文件。

精明的读者会注意到你可以轻松地用RAILS_ENV代替subdomain ……

为什么不使用视图中内置的rails?

在您的控制器中添加此方法:

 class StaticPagesController < ApplicationController def robots render :layout => false, :content_type => "text/plain", :formats => :txt end end 

在视图中创建一个文件: app/views/static_pages/robots.txt.erb其中包含robots.txt内容

routes.rb

 get '/robots.txt' => 'static_pages#robots' 

删除文件/public/robots.txt

您可以根据需要添加特定的业务逻辑,但这样我们就不会读取任何自定义文件。

对于Rails 3:

创建一个控制器RobotsController:

 class RobotsController < ApplicationController #This controller will render the correct 'robots' view depending on your subdomain. def robots subdomain = request.subdomain # you should also check for emptyness render "robots.#{request.subdomain}" end end 

创建机器人视图(每个子域1个):

  • 视图/机器人/ robots.subdomain1.txt
  • 视图/机器人/ robots.subdomain2.txt
  • 等等...

在config / routes.rb中添加新路由:(注意:txt格式选项)

 match '/robots.txt' => 'robots#robots', :format => :txt 

当然,您应该在config / initializers / Mime_types.rb中声明:txt格式:

 Mime::Type.register "text/plain", :txt 

希望能帮助到你。

如果您在将请求发送到rails之前无法配置您的http服务器,我只需设置一个“机器人”控制器,呈现如下模板:

 def show_robot subdomain = # get subdomain, escape render :text => open('robots.#{subdomain}.txt').read, :layout => false end 

根据您要完成的任务,您还可以使用单个模板而不是一堆不同的文件。

我喜欢TA Tyree的解决方案,但它非常以Rails 2.x为中心,所以这就是我为Rail 3.1.x提出的

mime_types.rb

 Mime::Type.register "text/plain", :txt 

通过在路由中添加格式,您不必担心在控制器中使用respond_to块。 的routes.rb

 match '/robots.txt' => 'robots#robots', :format => "text" 

我在这个上添加了一些额外的东西。 搜索引擎优化人员抱怨子域和SSL页面中的重复内容,因此我创建了一个用于生产的两个机器人文件和一个用于生产的机器人文件,这些文件也将用于生产中的任何SSL / HTTPS请求。

robots_controller.rb

 class RobotsController < ApplicationController def robots site = request.host protocol = request.protocol (site.eql?("mysite.com") || site.eql?("www.mysite.com")) && protocol.eql?("http://") ? domain = "production" : domain = "nonproduction" robots = File.read( "#{Rails.root}/config/robots-#{domain}.txt") render :text => robots, :layout => false end end