ruby-on-rails 如何将子域Map到localhost中的现有控制器操作

r1zk6ea1  于 4个月前  发布在  Ruby
关注(0)|答案(7)|浏览(79)

我想有一个子域名为这个特定的路线

get 'product_list/home'

字符串
以前的网址用来像localhost:3000/product_list/home。现在我希望网址是store.dev:3000/product_list/home
我把路线修改成这样

constraints subdomain: 'store' do 
      get 'product_list/home'
    end


在/etc/hosts中,我添加了一个store.dev,如下所示

127.0.0.1   localhost
127.0.0.1   store.dev


但是当在开发环境中访问store.dev:3000时,我得到的主页就像localhost:3000一样。
但我想限制我的子域只有这个路由product_list/home
还有一个问题是
http://store.dev:3000/product_list/home当我访问这个
我去拿

No route matches [GET] "/product_list/home"


最新消息:
将主机文件中的条目从store.dev更改为store.local.dev后,它可以正常工作,我可以访问store.local.dev:3000/product_list/home.但我的问题是我也可以访问其他页面,比如我有about页面. store.local.dev:3000/about,但我不希望发生这种情况。如何将子域限制为只有一个特定的路由

jm81lzqq

jm81lzqq1#

您的示例和大多数其他答案中的示例实际上根本没有使用子域:如果您查看域名store.dev,则它实际上没有子域,store.dev是顶级/根域。子域的示例是:sub.store.dev
如果您将 /etc/hosts 文件中的条目从store.dev更改为store.local.dev,则代码将正常工作。

更新

要回答问题的第二部分(将路由限制在根域):您可以通过将应该仅在根域上可用的路由 Package 在另一个带有空子域的constraints块中来实现这一点:

constraints subdomain: '' do
  get '/about'
end

字符串

ar7v8xwq

ar7v8xwq2#

您的路由文件代码正确
第一个月
对于测试localhost使用以下网址没有必要做主机文件store.lvh.me:3000的变化
lvh.me是与127.0.0.1Map的虚拟域名
https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains

1mrurvl1

1mrurvl13#

我认为你需要将子域也添加到/etc/hosts文件中:

127.0.0.1   dev items.dev

字符串

1u4esq0p

1u4esq0p4#

请尝试在/etc/hosts中添加一个DNS子域:

127.0.0.1 *.dev

字符串
或者,只需导航到http://items.lvh.me。(此域的所有者当前将域和子域的所有DNS请求指向127.0.0.1)
此外,在启动服务器时,您可能需要绑定到正确的接口,因为127.0.0.1并不严格等同于localhost(默认情况下,rails服务器绑定到localhost):

rails s -b 127.0.0.1


rails s -b 0.0.0.0 # all interfaces


请注意,后者可能被认为是不安全的,因为它会将开发服务器暴露给本地网络。

pobjuy32

pobjuy325#

我添加了另一个答案,因为问题已经从原来的改变,我现有的答案不再相关。
为了确保您的子域名store.domain.dev只有一个可用的路由,您还需要将其余的路由封装在一个约束块中:

# this matches store.domain.dev
constraints subdomain: 'store' do 
  get '/product_list/home'

  # add a redirect for the root path so you don't get a 404 
  # when browsing to store.domain.dev (optional)
  root '/', to: redirect('/product_list/home')
end

# this matches no subdomain and 'www' subdomain (i.e. domain.dev and www.domain.dev)
constraints subdomain: /^(|www)$/ do
  # put ALL your other routes here
  # ..
  # root '/', to: 'home#index'
end

字符串
对于问题的第二部分,您应该尝试使用domain.dev而不是仅使用dev,否则子域可能会被错误地解释。
此外,您可能应该使用get '/product_list/home',而不是Rails路由指南中指定的get 'product_list/home'http://guides.rubyonrails.org/routing.html

pu82cl6c

pu82cl6c6#

Docs

基于请求的约束

您还可以基于返回String的Request对象上的任何方法来约束路由。
指定基于请求的约束的方法与指定段约束的方法相同:
第一个月
也可以在块形式中指定约束:

namespace :admin do
  constraints subdomain: 'admin' do
    resources :photos
  end
end

字符串

更新:

我找到了this link,它提供了一种在开发机器上创建子域路由的方法。如果这也不能解决你的问题,还有另一种方法here

rekjcdws

rekjcdws7#

下面的设置对我很有效
在config/environments/development.rb中设置config.action_dispatch.tld_length = 0
参考:https://gist.github.com/indiesquidge/b836647f851179589765

相关问题