Search code examples
ruby-on-railsamazon-web-servicesrails-activestorage

how to hide the ugly aws s3 url - RoR app


My RoR app is on Heroku and active storage is configured correctly. However, when I'm in the app and fetch the uploaded document, the url is something like https://cremers.s3.eu-west-1.amazonaws.com/cx9xy0pmbieagvuw8a0vzcnfhvcc?response-content-disposition=inline%3B filename%3D"Digeste_9.1.pdf"%3B....

How to change this to a "normal" url, like https://www.cremers.fr/documents/digest_9.1.pdf ?


Solution

  • You can use a route/controller to act as a sort of proxy. I've done exactly this, below is roughly the code I used, edited for your specifics.

    I did not test this with your settings, obviously, and I wasn't using ActiveStorage in my case, so you might need/want to adjust, but this should get you started:

    # config/routes.rb
    Rails.application.routes.draw do
      get '/documents/:filename.:format.:compression', to: 'documents#show'
    end
    
    # app/controllers/documents_controller.rb
    
    require 'open-uri'
    
    class DocumentsController < ApplicationController
      def show
        bucket_name = 'cremers'
        aws_region = 'eu-west-1'
        filename = params[:filename]
        s3_url = "https://s3-#{aws_region}.amazonaws.com/#{bucket_name}/#{filename}"
        data = open(s3_url)
        send_data data.read, type: data.content_type
      end
    end