Skip to main content

How do I create my homepage subdomain ('www')

Rails • Asked by Damian Nelwep


I followed the tutorial for subdomain from scratch and got " redirect_to root_url(subdomain: "www") if @account.nil? " but I don't know how to get to manage it as a homepage like home#index.

I wondered if I wouldn't have to change something about " before_action :set_account " in application_controller.rb

thank you in advance

Hey Damian!

It's usually easiest to set that up in your routes file. You can setup a subdomain constraint so that when the subdomain is www or nil, you can render the homepage. Otherwise when there's a subdomain, you can send it to the account controller.

You can put this in app/lib/account_subdomain.rb

class AccountSubdomain
    def self.matches? request
          # www and no subdomain are excluded and don't count as account subdomains
            # You can add any more subdomains to this array to have them ignored.
          !["www", nil].include? request.subdomain

Then your config/routes.rb file can use this to set the constraints:

Rails.application.routes.draw do
    # Account routes
    constraints(AccountSubdomain) do
            root to: "account#index"

        root to: "home#index"

Thank you but I get an error

uninitialized constant AccountSubdomain

Is it normal that I had to create the directory lib/ in the app/ folder ?

I also get
Routing Error
No route matches [GET] "/"

Sorry in fact I just had to restart the server and now it works perfectly thank you so much...

I only have a last issue which is that when I'm in a subdomain and I get to 'home', the subdomain still appear in the url whereas I want 'www' or nil.. :s

I get '' instead of '' or ''

You can pass subdomain: nil into your url helpers to change the subdomain. Something like link_to home_url(subdomain: nil)

Thank you again this is perfectly what I needed. You're the best teacher I could ever dream of but I hope I don't bother you so much with my issues... By the way I think I would be interested in your hosting service but I'll ask you about it later, now is not the time. Hope you're having a good day :)

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.