ruby-on-railsnginxnginx-reverse-proxyruby-on-rails-7

Dropping a part of the URL in Rails


I have a setup where I route all requests for /upload/* to Rails. Using the blog example, I want somedomain.com/upload/article/new to be treated as somedomain.com/article/new by Rails. I ended up with the following.

routes.rb

Rails.application.routes.draw do
  root "articles#index"
  scope 'upload' do
    resources :articles do
      resources :comments
    end
  end
  resources :articles do
    resources :comments
  end
end

nginx.conf

location /upload/ {
            proxy_pass http://localhost:3000/;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
    }

It works, but you can clearly see the same code written twice right next to each other. I was wondering if there's a more proper way to do this.


Solution

  • You can define a helper method:

    Rails.application.routes.draw do
      def uploadable
        # yield first outside the scope so that your helper methods
        # generate urls without "/upload" prefix (since you don't want it anyway)
        yield
        scope "upload" do
          yield
        end
      end
    
      uploadable do
        resources :articles do
          resources :comments
        end
      end
    end
    

    You can also try making "upload" part optional:

    Rails.application.routes.draw do
      scope "(/upload)" do
        resources :articles do
          resources :comments
        end
      end
    end