简体   繁体   中英

Ruby on Rails redirect to www. only if no subdomain is present

I'm trying to redirect to www. only if another subdomain is not present.

If the url is example.com then I want to redirect to www.example.com

If the url is blog.example.com then I don't want to redirect.

I have tried this but it add www. to every url even if another subdomain is already present.

constraints(host: /^(?!www\.)/i) do
  get '' => redirect { |params, request|
    URI.parse(request.url).tap { |uri| uri.host = "www.#{uri.host}" }.to_s
  }
end

I think i need to check subdomain.present? somewhere but not sure where.

Any ideas?

This is what worked for me. There might be a better way to go about it though.

  constraints(subdomain: '') do
    constraints(host: /^(?!www\.)/i) do
      get '' => redirect { |params, request|
        URI.parse(request.url).tap { |uri| uri.host = "www.#{uri.host}" }.to_s
      }
    end
  end

I did the following in my application controller (Rails 6):

class ApplicationController < ActionController::Base
  before_action :ensure_www
  
  # Other stuff

  protected
  def ensure_www
    if request.subdomain != 'www'
      redirect_to url_for(subdomain: 'www', only_path: false)
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM