2013-04-25 16 views

Trả lời

6

Trích dẫn từ https://devcenter.heroku.com/articles/custom-domains

Các myapp.herokuapp.com miền sẽ luôn duy trì hoạt động, ngay cả khi bạn đã thiết lập một miền tùy chỉnh. Nếu bạn muốn người dùng chỉ sử dụng tên miền tùy chỉnh , bạn nên gửi trạng thái HTTP 301 Đã di chuyển Vĩnh viễn để yêu cầu trình duyệt web sử dụng miền tùy chỉnh. Yêu cầu HTTP máy chủ lưu trữ trường tiêu đề sẽ hiển thị tên miền mà người dùng đang cố gắng truy cập; gửi chuyển hướng nếu trường đó là myapp.herokuapp.com.

Bạn có thể chuyển hướng yêu cầu tới "subdomain.herokuapp.com" bằng bộ lọc trước trong ApplicationController hoặc sử dụng hạn chế trong định tuyến đường ray.

2

Để có câu trả lời toàn diện với một chút khả năng mở rộng, tính tổng thể, nó trông giống như thế này;

class ApplicationController < ActionController::Base 

    before_filter :redirect_to_example if Rails.env.production? 

    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 

    private 

    # Redirect to the appropriate domain i.e. example.com 
    def redirect_to_example 
     domain_to_redirect_to = 'example.com' 
     domain_exceptions = ['example.com', 'www.example.com'] 
     should_redirect = !(domain_exceptions.include? request.host) 
     new_url = "#{request.protocol}#{domain_to_redirect_to}#{request.fullpath}" 
     redirect_to new_url, status: :moved_permanently if should_redirect 
    end 
end 

Điều này sẽ chuyển hướng mọi thứ đến domain_to_redirect_to ngoại trừ những gì trong domain_exceptions.

+0

hoạt động cho đường dẫn, nhưng không cho trang chủ – linojon

+1

@ linojon Dường như nó hoạt động với tôi trên đường dẫn gốc, nhưng tôi đã thay đổi new_url thành '{# request.protocol} # {domain_to_redirect_to} # {request. fullpath nếu request.fullpath! = '/'} "' để tránh dấu gạch chéo. – eirikir

+0

Cũng giống như thêm một ... Tôi không biết về 'loại trừ? 'Khi tôi viết điều này ... bạn có thể có,' should_redirect = domain_exceptions.exclude? request.host' có vẻ dễ đọc hơn. –

Các vấn đề liên quan