Make sure that this is your year by checking the Startup Web Guide for 2019 that we’ve put together for all new businesses out there!

Protect Ruby on Rails apps with Passenger and Nginx

This article is intended to explain the complete process of password protecting your website with Passenger and Nginx. I'll assume that the website is already running, but not password protected.

When we start working on a new project, it first gets deployed to what we call a staging environment. The objective is to allow the customer to evaluate the progress of the project.

In order to keep things private and prevent Google and other search engines from indexing the site too soon, we need to password protect it. There's already some information out there on how to achieve this with Nginx, but to figure it out, I needed to dig into several sites.

To clarify, the framework stack is consisted by:

  • Ruby on Rails
  • Passenger
  • Nginx

Because the server is already running, there should be a server section on the nginx.conf file similar to this:

server {
        listen       80;
        server_name  staging.example.com;
        rails_env staging;
        root /home/foo/example.com/current/public; 
        passenger_enabled on;
 }

In order to password protect an existing site, we need to first generate a password file. The easiest way is to use a web application such as the Htpasswd Generator. Store the generated text in a file in the server.

Now, edit the nginx.conf file again and change the server section to:

server {
        listen       80;
        server_name  staging.example.com;
        rails_env staging;
        root /home/foo/example.com/current/public; 
        passenger_enabled on;

        #password protect
        location ~ / {
                 auth_basic            "Restricted";
                 root /home/foo/example.com/shared/.htpasswd;
                 passenger_enabled on;
        }
}

Paste the location of your .htpasswd file at: /home/foo/example.com/shared/.htpasswd;

Notice the passenger_enabled entry inside the password protect section. This entry is needed to trigger Passenger after completing the password authentication process.

Otherwise the server will try to list the web root directory, and probably show an unauthorized error.

This is really all it takes to password protect your Rails app with Passenger and Nginx.

At Imaginary Cloud, we simplify complex systems, delivering interfaces that users love. If you’ve enjoyed this article, you will certainly enjoy our newsletter, which may be subscribed below. Take this chance to also check our latest work and, if there is any project that you think we can help with, feel free to reach us. We look forward to hearing from you!