Hosting a static website on DigitalOcean Spaces

In my previous blog post I wrote about DigitalOcean Spaces and how to integrate them with Rails’ ActiveStorage. After I successfully tested the integration I was curious: Can we host static websites on DigitalOcean Spaces, too?

Yes we can!

But unfortunately DigitalOcean Spaces don’t support Index documents in contrast to AWS S3. But it seems that DigitalOcean is working on this functionality/compatibility:

We are still hoping to deliver this kind of functionality before end of year. Sorry I don’t have better / more news at this point.

Let’s see if we can bypass this functionality with a “clever” nginx configuration:

server {
	server_name 		example.com;

	set $bucket "your-bucket.region.digitaloceanspaces.com";

	location ~* \.(jpe?g|png|gif|ico|css|js|json|map)$ {
		resolver 8.8.8.8;
		rewrite ^([^.]*[^/])$ $1/ permanent;
		proxy_pass https://$bucket${uri};
	}

	location / {
		resolver 8.8.8.8;
		proxy_pass https://$bucket/index.html;
	}

Okay this is not really clever but it gets the job done for a single page application (SPA):

  • All assets are served by their “original” URI from the root bucket directory.
  • All other requests are “redirected” to the /index.html in the root directory.

For a website with multipe subdirectories you would need change this nginx config a little bit - but it should not be too complicated.

See ya!

ActiveStorage with DigitalOcean Spaces

You are developing a Rails 5.2 application with ActiveStorage and don’t want to use AWS S3? You can also use DigitalOcean’s Spaces since it’s S3 compatible. Here’s a short example on how to store your assets on DigitalOcean Spaces:

1. Add the aws-sdk-s3 gem to your Gemfile:
gem 'aws-sdk-s3'
2. Don’t forget to bundle:
bundle
3. Add a DigitalOcean storage provider block in your config/storage.yml:
digitalocean:
  service: S3
  access_key_id: <%= ENV.fetch('ACCESS_KEY')% >
  secret_access_key: <%= ENV.fetch('SECRET_ACCESS_KEY') %>
  region: <%= ENV.fetch('REGION') %>
  bucket: <%= ENV.fetch('BUCKET_NAME') %>
  endpoint: 'https://ams3.digitaloceanspaces.com'

This leaves us with four env variables that must be set:

  • ACCESS_KEY: The access key can be obtained from the DigitalOcean settings.
  • SECRET_ACCESS_KEY: The be generated along the ACCESS_KEY.
  • REGION: The region that you’ve selected during the bucket creation (e.g. ams3).
  • BUCKET_NAME: The bucket name you’ve chosen.
4. Set the new storage provider for your environment:

In your config/environments/development.rb switch the :local provider with the new :digitalocean one.

config.active_storage.service = :digitalocean
5. Start uploading files to DigitalOcean Spaces!