I am using Nginx server with a RoR webapplication (version 6.1.4).
I have several audio files around the site and I want to restrict direct access to them. The page have publicly accessible part and another for registered members. Here they can upload and share mp3's through the platform.
I added the following lines to nginx configuration:
location ~* \.mp3 {
valid_referers server_names;
if ($invalid_referer) {
return 403;
}
}
This one is working fine for the hardcoded audios and prevents direct access.
But if someone logs in and traces the html for the sourcefiles of uploaded audios, it is still accessible for them. I am using ActiveStorage for managing file uploads and it is on a s3 storage.
Appreciate any ideas!
CodePudding user response:
Did not check, but customize this and try:
location ~* \.mp3 { # location for .mp3 files
if (-f $request_filename) { # if file actually exists
return 301 $scheme://$server_name/RoR_APP_URI_with_auth_check/$request_uri;
}
}
CodePudding user response:
This could be a good opportunity to use the Proxy design pattern. You could create a controller/action that handles user authentication and then either redirects to the appropriate url or directly serves the file using send_file
. There are pro's and con's to this approach but it would be a way to authenticate requests and restrict access to paywalled content.
Here's an example from a production app I'm working on:
def avatar_proxy
if Rails.env.development?
tmp_file = open(current_user.avatar.path)
else
url = current_user.avatar.url
tmp_file = open(url)
end
send_file tmp_file, :type => current_user.avatar.content_type, disposition: 'inline'
end