LoginSignup
0
0

More than 5 years have passed since last update.

nginxとcarrierwaveを使ってサーバー上の任意の箇所に画像を保存する

Last updated at Posted at 2018-07-04

Capistranoを使ってサーバー上にデプロイすると、毎回別のディレクトリができて、
currentフォルダからのショートカットになりますが、
carrierwave等でプロジェクト内に画像等を保存している場合はそれじゃ困ると思いますので、
別パスに保存したい。
(S3等に保存していて気にしていない人がほとんどかもしれませんが。。。)

プロジェクト内の任意のパスに画像を保存するには下記の設定を変えればできたので、
備忘として残しておきます。

/etc/nginx/conf.d/app.conf
    location / {
      try_files $uri/index.html $uri.html $uri @unicorn;
    }

    location @unicorn {
      # HTTP headers
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto https;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_pass http://ドメイン;
    }

        # ここで画像を保存したいパスを指定
    location /home/app/uploads {
      root /;
    }

これで「https://ドメイン/home/app/uploads/…」等にアクセスされた時は
サーバー内の「/」がルートパスとなるので、
「/home/app/uploads」配下を見に行くようになります。

で、プロジェクト内のuploaderファイルのstore_dirを下記のように変えます。

image_uploader.rb
  def store_dir
    #"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    "/home/app/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

これで「/home/app/uploads」配下に画像をアップロードするようになりました。
あ、「/home/app/uploads」のアクセス権限を正しく設定するのをお忘れなく。

もっといい方法があれば教えて下さい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0