Rails开发模式下为public目录视频文件设置Accept-Ranges:none HTTP头
Hey there! Let's tackle this problem step by step. Your initial attempt with config.public_file_server.headers in development.rb does add those headers, but it applies to all static files in the public directory—not just your target video. Here are two precise ways to set Accept-Ranges: none only for /public/videos/example.mp4 in development mode:
Option 1: Serve the video via a controller (most straightforward)
This approach lets you explicitly control the response headers for just this video by routing requests through a Rails controller action:
- First, add a route in
config/routes.rbto map the video URL to a controller action:get '/videos/example.mp4', to: 'videos#serve_example' - Generate a dedicated controller (skip unnecessary files to keep it clean):
rails generate controller Videos serve_example --skip-assets --skip-helper --skip-template-engine - Open
app/controllers/videos_controller.rband implement theserve_examplemethod to set your custom headers and send the file:class VideosController < ApplicationController def serve_example # Define the full path to your video file video_path = Rails.root.join('public', 'videos', 'example.mp4') # Set your desired response headers response.headers['Accept-Ranges'] = 'none' response.headers['Cache-Control'] = 'public, max-age=15768000' # Send the file with inline disposition (so it plays in the browser) send_file video_path, disposition: 'inline', type: 'video/mp4' end end - Restart your Rails development server, then visit
/videos/example.mp4—you should see theAccept-Ranges: noneheader in your browser's dev tools network tab.
Option 2: Use a Rack middleware (no controller required)
If you prefer not to add a new controller and route, a custom Rack middleware can intercept requests to the specific video path and modify the response headers:
- Create a new middleware file at
app/middleware/modify_video_headers.rb:class ModifyVideoHeaders def initialize(app) @app = app end def call(env) # Pass the request through the Rails stack first status, headers, response = @app.call(env) # Check if the request is for your target video if env['PATH_INFO'] == '/videos/example.mp4' # Override or add the desired headers headers['Accept-Ranges'] = 'none' headers['Cache-Control'] = 'public, max-age=15768000' end # Return the modified response [status, headers, response] end end - Register the middleware in
config/environments/development.rb(add this inside theRails.application.configure doblock):config.middleware.use ModifyVideoHeaders - Restart your dev server, and test the video URL—your custom headers should now be present.
Quick note on your original config
If you ever did want to apply these headers to all static files in public, your original config.public_file_server.headers setup was correct. But since you only need it for one video, the above methods are more targeted.
内容的提问来源于stack exchange,提问作者Cannon Moyer

