Redirecting Subdomains in Rails

February 24, 2015

There are many reasons why you may want to re-route your domain at the application level inside your rails app.

One reason we decided to do this at Fanpics was because of the limitations of using DNS redirects.

DNSimple lists this specific option as an invalid redirect

https://example.com => https://www.example.com

The technical explanation behind this is that URL forwarding isn’t actually a DNS record type but is instead an A record that points to an HTTP server.

To overcome this limitation I added a few simple lines to the /app/controllers/application_controller.rb.

This is done by calling a method to check if the url needs to be redirected through the before_action statement.

An example of this would be:

1
2
3
4
5
6
7
8
9
before_action :ensure_domains

protected

def ensure_domains
  if Rails.env.production? && request.subdomain != 'www'
	  redirect_to request.url.sub(//“,”//www.)
	end
end

So what does all of this do?

First, since the application controller is in the base controller class of the application and run on every controller it would properly point to the correct url through ssl for each request.

So if you were to make a request that wasn’t on the correct subdomain and through http it would redirect to https then add the proper subdomain.

The ensure_domain first checks to see if the Rails environment is running on production. This redirect is probably not needed for your development environment and may even break it depending on how you have it configured.

The second check just checks to see if it is already on the proper subdomain.

Now it simply grabs the request url and parses out // and replaces it with //www.