Search code examples
nginxruby-on-rails-3.2basic-authenticationunicorn

Rails 3.2 Nginx Unicorn Basic Authentification


I am trying to get Basic Authentification to work with Rails 3.2 nginx and Unicorn

The configuration works for hosting my site. I used the Rails Basic Authentification in the Controller but i have to many problems while testing. The .htpasswd file is also working i could restrict the access to a static site.

In the location config i tried

location /
location /home/deployer/apps/rails/current/public
location /home/deployer/apps/rails/current/

Any ideas?

This is my config:

upstream unicorn {
  server unix:/tmp/unicorn.blog.sock fail_timeout=0;
}

server {
  listen 80 default deferred;
  server_name railsserver;
  root /home/deployer/apps/rails/current/public;

  location / {
    auth_basic "Restricted";
    auth_basic_user_file /var/www/prototyp/.htpasswd;
  }

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

I tried it with this config now but it does not work

server {
  listen 80 default deferred;
  server_name rails.com;
  root /home/deployer/apps/rails/current/public;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri /;

  location / {
    auth_basic "Restricted";
    auth_basic_user_file /var/www/prototyp/.htpasswd;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

Solution

  • Do it like this to get it to work:

    location / {
        auth_basic "Restricted";
        auth_basic_user_file /var/www/prototyp/.htpasswd;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://unicorn;
    }
    

    You don't need the @unicorn location