loading css files within a static website in heroku

heroku, rack, ruby

Solution

Your app currently responds to requests in two different ways. Requests starting with `/images` are served by searching the `/public/images` folder and returning any file matching the request. Any other request is served by running the `lambda` block, which returns your `index.html` file with a content type of `text/html`.

This applies to any other request, so when your page references a css file and the browser tries to fetch it, your app will return the `index.html` page with the HTML content type, hence the warning about MIME type.

One way to fix this would be to add `/css` to the list of urls the `Static` middleware handles:

use Rack::Static, 
  :urls => ["/images", "/css"],
  :root => "public"

and put your css files in the `public/css` directory (as I write, it looks like you have already done this).

This would solve your immediate problem, but you might have issues for example if you wanted to have more than one HTML page in the top directory.

Another solution to achieve a static site that serves `index.html` to any requests with no path, which is what it looks like you're trying to do here, could be to use the `rack-rewrite` gem and a `Rack::File` application. Add `gem 'rack-rewrite'` to your Gemfile, and then use a `config.ru` like this:

require 'rack/rewrite'

use Rack::Rewrite do
  rewrite "/", "/index.html"
end

run Rack::File.new("public")

This will respond to all requests with the matching file (if it exists), and any requests that arrive with no path will get `index.html`. (Note that it won’t serve `index.html` for requests for subdirectories under the main directory).

If you’re using Heroku’s Cedar stack, you could also look into faking a php app in order to get “real” static hosting with Apache.

I don’t know why this would be working locally but not on Heroku, unless you’re just opening the files directly in the browser. Are you running a server locally (e.g. with `rackup`), or looking at the files direct?

Problem

My `config.ru` is as follows: ``` use Rack::Static, :urls => ["/images"], :root => "public" run lambda { |env| [ 200, { 'Content-Type' => 'text/html', 'Cache-Control' => 'public, max-age=86400' }, File.open('public/index.html', File::RDONLY) ] } ``` When I load it locally the website looks fine, but when I run it on Heroku I get the following error message in the browser console for the CSS files: ``` Resource interpreted as Stylesheet but transferred with MIME type text/html. ``` Any idea why I am getting these errors? Example site: http://salus8.heroku.com.

Original source