Search code examples
ruby-on-railsrubyamazon-s3amazon-cloudfront

How do I send a user an HTML file from S3 or Cloudfront using Rails?


I want to simply re-route the user to a page (say bucket.amazons3.com/hello.html) while still making it appear as if they are on DOMAIN.COM/hello.html ... I want to do this say if a certain IF condition passes..

eg:

if (RAILS == "cool") && (S3.exists?("hello.html"))
 send_to_s3
end

where "send_to_s3" simply redirects the user to Amazon Cloudfront or S3 and renders the "hello.html" page in their browser. But they feel like they never left my website..

Now imagine I want to do this same behavior with Hello1.html, Hello2.html, Hello3.html..... Hello20Million.html...

How can I do this efficiently without significantly increasing my server load?

How would I do this in RAILS running on server like Thin/Puma/Webrick?


Solution

  • There are two ways you could go about doing this:

    1. Using iframes in your view which point to the S3 URL.
    2. Doing a server side request to the amazon URL and rendering the response as if it is one of your rails views.

    The first option is quite simple. If your condition is satisfied you open one of your rails views which has an embedded iframe with its src attribute pointing to the S3 URL. You will have to take care of the iframe dimensions (width x height) dynamically in JS to give the user a seamless experience (window resize etc).

    In the second option you can actually request for the S3 URL through ruby using open-uri and then render the response you get into your own view. To request for the file URL use the following code:

    require 'open-uri'
    url_response = open('http://example.com/file_to_read.htm').read
    

    In your view you need to render the url_response:

    <%= url_response.html_safe %>
    

    Using html_safe you tell rails that you want to output the string as is without any encoding to make it html safe.

    Using either of these options will make it appear as though the request is coming from your server.

    P.S: I was also wondering that it is also possible to do this via URL rewriting or proxy pass using .htaccess or similar but in your question you have specifically asked about "Rails".