You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5.2.1 Apache环境下Active Storage HTTP请求超时问题求助

问题

在Apache上运行的Rails 5.2.1服务器中,请求Active Storage存储的图片时,HTTP协议下会超时,但HTTPS协议下可正常加载。其余功能均正常,仅Active Storage生成的链接无法加载。

因兼容性需求,必须继续使用HTTP。尝试添加重写规则将请求重定向至HTTPS,但无效果,请求仍超时。

尝试过的Apache重写规则

RewriteEngine on
RewriteCond %{SERVER_PORT} =80
RewriteRule ^(rails/active_storage)$ https://myserver.com/$REQUEST_URI [R=301,L,NC]

Active Storage相关代码

模型代码

has_many_attached :images   
def thumbnail()
  if (self.images.length > 0)
    return self.images[0].variant(resize: "200x200").processed
  end
end

Jbuilder代码

json.thumbnail url_for(post.thumbnail())

解决方案

1. 修正Apache重写规则

当前的RewriteRule匹配规则仅能精确匹配/rails/active_storage路径,但Active Storage的实际请求路径是/rails/active_storage/blobs/xxxx/xxx.jpg这类带后缀的格式,所以需要调整匹配模式:

RewriteEngine on
RewriteCond %{SERVER_PORT} =80
RewriteRule ^rails/active_storage/(.*)$ https://myserver.com/rails/active_storage/$1 [R=301,L,NC]

或者用更简洁的写法直接匹配前缀:

RewriteEngine on
RewriteCond %{SERVER_PORT} =80
RewriteRule ^rails/active_storage/ https://myserver.com%{REQUEST_URI} [R=301,L,NC]

2. 让Rails直接生成HTTPS的Active Storage链接

如果重写规则仍无效,可在config/environments/production.rb中配置,强制url_for生成HTTPS链接:

Rails.application.routes.default_url_options[:protocol] = 'https'

这样网站其他部分仍可通过HTTP访问,仅Active Storage的图片链接直接用HTTPS加载,绕开HTTP超时问题。

3. 检查Apache反向代理配置(若使用代理)

如果Rails是通过Apache反向代理运行的,需确保Apache正确传递协议头,在代理配置中添加:

RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Ssl on

同时在config/environments/production.rb中补充:

config.action_dispatch.default_headers = {
  'X-Forwarded-Proto' => 'https'
}
config.force_ssl = false # 保持HTTP访问可用

内容的提问来源于stack exchange,提问作者Pingou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:48:23