dior001
dior001

Reputation: 761

Prevent subdomain access for html requests

I have a subdomain widgets.mywebsite.com. The only thing the subdomain does is return json on a given route. How do I prevent people/crawlers accessing my site via the subdomain whilst still keeping the route available? I would be happy to simply redirect any requests that include this subdomain to mywebsite.com but can't work out how to do it.

constraints :subdomain => 'widgets' do
  namespace :widgets, :path => nil, :format => 'json' do
    match 'v1' => 'v1/widgets#index'
  end
end

Upvotes: 3

Views: 159

Answers (1)

Peter Goldstein
Peter Goldstein

Reputation: 4545

So it sounds like you want to reverse the logic in your routes - you want to constrain the bulk of your routes so that they only resolve when the subdomain isn't equal to widgets. That's opposed to the above example, where you're making a single route only available on the 'widgets' subdomain. This is pretty straightforward.

In your config/routes.rb you can define a class before the Application.routes.draw block

class NotWidgetsRequest
  def matches?(request)
    request.subdomain != 'widgets'
  end
end

and then you can wrap all of your routes other than the v1/widgets#index route in a

constraints NotWidgetRequest.new do 
  ...
end

block. This will prevent these routes from resolving on widgets.mywebsite.com

Upvotes: 3

Related Questions