[英]How do I remove a subdomain from URL?
I followed the Railscast on adding subdomains to a Rails app, here , and everything is working great with the subdomains. 我跟随Railscast将子域添加到Rails应用程序中, 在这里 ,所有工作都与子域一起很好。 Now I just can't figure out a way to link back to the root domain without a subdomain if the requested subdomain does not exist.
现在,如果请求的子域不存在,我只是想不出一种方法来链接回没有子域的根域。
I've tried adding the following to my application_controller.rb
file 我尝试将以下内容添加到我的
application_controller.rb
文件中
redirect_to root_path(subdomain: false) if @city_or_state.nil?
where @city_or_state
determines weather the requested subdomain is valid. 其中
@city_or_state
确定所请求的子域有效的天气。 The redirect_to
goes back to the root, but does not remove the subdomain. redirect_to
返回到根,但不会删除子域。
For example, if a user tries to go to invalid.domain.com
they are redirected to the root, but subdomain is not removed. 例如,如果用户尝试转到
invalid.domain.com
,则会将其重定向到根目录,但不会删除子域。
I'm trying to get invalid.domain.com
to redirect to domain.com
我正在尝试使
invalid.domain.com
重定向到domain.com
Ok, I got it. 好,我知道了。 I had to use the following:
redirect_to root_url(:host => request.domain)
我必须使用以下命令:
redirect_to root_url(:host => request.domain)
When I tried root_path(:host => request.domain)
it didn't work. 当我尝试
root_path(:host => request.domain)
它不起作用。 Only works with root_url
. 仅适用于
root_url
。
I found the answer on some comments from Daniel Kehoe here 我找到了答案,从丹尼尔·基欧一些意见在这里
When attempting to visit a domain that does not exist, the invalid subdomain is removed from the URL. 尝试访问不存在的域时,无效的子域将从URL中删除。
You can try this way i think it works! 您可以尝试这种方式,我认为它可行! In the application_controller.rb you can add a
before_filter :validate_subdomain
Then you add this code to the controller: 在application_controller.rb中,您可以添加一个
before_filter :validate_subdomain
然后将此代码添加到控制器中:
private
def validate_subdomain
# @city_or_state must be initialized before this
if @city_or_state.nil?
redirect_to request.domain
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.