LoginSignup
3

More than 5 years have passed since last update.

nginx + unicornを使用している時に特定ディレクトリ以下に対してIP制限をかける

Last updated at Posted at 2015-08-03

unicornを使用している状態で、通常のnginxの制限を書こうとすると、unicornにプロキシされずアクセス時にnot foundとなってしまいます。そんな時の回避方法が以下となります。

upstream unicorn {
  server unix:/tmp/unicorn.sock;
}

server {
  listen 80 default_server;
  server_name myapp.com;

  access_log /var/www/myapp/logs/access.log;
  error_log /var/www/myapp/logs/error.log;

  root /var/www/myapp/source;

  // ここでELBのIPをクライアントのIPに置き換え
  set_real_ip_from 10.0.0.0/8;
  real_ip_header  X-Forwarded-For;

  // 制限をかけるディレクトリを指定
  location /admin/ {
    // アクセス元IP指定
    allow xxx.xxx.xxx.xxx;
    deny all;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_pass http://unicorn;
  }

  location ~ ^/assets/ {
    root   /var/www/myapp/source/public;
  }

  client_max_body_size 100m;
  error_page 404 /404.html;
  error_page 500 502 503 504 /500.html;
  try_files $uri/index.html $uri @unicorn;

  location @unicorn {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_pass http://unicorn;
  }
}

参考

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
3