0

I have a Rails application (http://example.org) where multiple tenants can have a simple CMS. They get a frontend which resides at http://example.org/frontend/clients/:client_name with relative sub-paths such as /posts and /media.

Now I wanted to allow tenants to use a custom domain, so the application will e.g. respond to a request to http://example.com/posts with the contents of http://example.org/clients/example.com/posts.

I managed to write an Nginx proxy_pass rule to get that working [see below]. The problem is now that the relative Rails link helpers which are served on http://example.com/posts (e.g. frontend_client_media_path) still point to the paths defined in Rails, e.g. http://example.com/clients/example.com/media.

Is there a possibility to tell Rails to construct the paths differently, by leaving out the /clients/example.com part, as long as the site is accessed by a custom domain?

Appendix

Nginx-Rule (the meat of it)

server {
  server_name _; # allow all domains

  location / {
    proxy_pass http://upstream/frontend/clients/$host$request_uri; # proxy to client-specific subfolder
  }
}
Lukas_Skywalker
  • 2,053
  • 1
  • 16
  • 28

1 Answers1

1

You could use a conditional in the routing that checks for the host and then loads a custom path.

Constraints based on domain/host Or Complex Parsing/Redirecting

constraints(host: /^(?!.*example.org)/) do
    # Routing
end

# http://foo.tld?x=y redirects to http://bar.tld?x=y
constraints(:host => /foo.tld/) do
    match '/(*path)' => redirect { |params, req|
        query_params = req.params.except(:path)
        "http://bar.tld/#{params[:path]}#{query_params.keys.any? ? "?" + query_params.to_query : ""}"
    }, via: [:get, :post]
end

Note: If you're dealing with full domains instead of just subdomains, use :domain instead of :host.

You can also include other logic to fine tune it for ex:

You could use controller_name or controller_path:

<% if controller_name.match(/^posts/) %>
    # Routing
<% end %>

<% if controller_path.match(/^posts/i) %> 
    # Routing
<% end %>
Community
  • 1
  • 1
blnc
  • 4,384
  • 1
  • 28
  • 42