ホーム > カテゴリ > Ruby・Ruby on Rails >

Active StorageのダウンロードURLを変更する[/rails/active_storage/blobs]

RailsのActive Storageでダウンロードリンクを作成するには「rails_blob_path」があります。通常に使用する分には問題ありませんが、Nginxのlocationなどでパスを切り分けている場合はダウンロードリンクを作成しても、404エラーでダウンロードできない状態になります。

Active Storageコントローラーのパスを変更する方法をご紹介します。

対策前

Railsアプリのパス

https://www.petitmonte.com/rails-demo/

rails_blob_pathが生成するダウンロードリンク

https://www.petitmonte.com/rails/active_storage/blobs/*

Nginxの設定 ※Unixドメインソケットを使用しない方法

server {
    listen       443 ssl;
    server_name  www.petitmonte.com;
    
    *** 省略 ***
    
    location /rails-demo {
      try_files $uri @rails_demo_app;    
    }
    location @rails_demo_app {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_pass http://localhost:3000;
    }    
}

解決方法

config/application.rbに次を記述するだけです。

config.active_storage.routes_prefix = '/rails-demo'

/rails-demoの部分は各自の環境に変更して下さい。

最終的にダウンロードリンクは次のようになります。

https://www.petitmonte.com/rails-demo/blobs/*

※config.active_storage.routes_prefixはRails6以上が必要です。





関連記事



公開日:2019年12月21日
記事NO:02813