Published on Oct 1, 2011

NginX Password Protect Web Directory

Protect Web Directory in Nginx

Protect Web Directory in Nginx

As you’ve installed and configured Nginx web server and also enabled https in the previous articles, now you might like to password protect your adminpanel web directory. To do that, you need to create a username and password in your server and store that in encrypted form in a secured htpasswd file. So let’s create the file using the following commands:

sudo apt-get install apache2-utils
htpasswd -b /usr/ssl/htpasswd NewUserName NewPassword

Now here replace the “NewUserName” and “NewPassword” with your desired username and password for accessing the protected folder. Now add the following configuration in the https server block. I’m assuming you’ll password protect the “adminpanel” directory in your web server root directory defined in the previous articles. So the configuration you’ll be adding will look like:

location ^~ /adminpanel/
{
auth_basic            "Restricted";
auth_basic_user_file  /usr/ssl/htpasswd;

location ~ \.php$
{
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:6000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/example.com/public_html$fastcgi_script_name;
fastcgi_param HTTPS on;
}
}

The location directive for php is needed here, otherwise php code inside that protected directory will not gonna work. Now let’s put this additional configuration inside the https server block in the /etc/nginx/sites-available/default file. As in the previous article we’ve configured the http requests for “adminpanel” directory to redirect to use https, so this will make our “adminpanel” directory password protected and also it’ll ensure that all requests to this directory uses https instead of http. So now we can put our important administration files in this directory and access them using the username and password set here. Now restart nginx for the configuration changes to take effect. Use the following command:

sudo service nginx restart

If that doesn’t work, then try this instead:

sudo /etc/init.d/nginx restart

Now let’s check if everything is working perfectly. In your browser’s address bar type http://your_ip_address/adminpanel/ and see if that properly redirects to https://your_ip_address/adminpanel/. It should also ask for a username and password. Then let’s play with it for sometime and when you are bored, come back again, in the next article we are going to setup PHP5 along with APC (Alternative PHP Cache) which is an advanced op-code caching system for PHP.

Articles in this Step by Step VPS Setup Guide

Getting Started with VPS – The Beginners Tutorial
Introductory concepts on web servers and virtual private servers. Introducing you to the world wide web from a technical point of view.

Shared Hosting, VPS, Dedicated and Cloud Servers
Comparing the popular server hosting solutions. Basic understanding of shared, dedicated, vps and cloud servers.

Deploy a Linux VPS Server using Linode
Tutorial on deploying your linux distribution in your VPS server and setting up hostname and initial configurations

Setup NginX Web Server (Not Apache!) on Ubuntu 10.04
Analyzing why NginX web server is better for you instead of the mostly used Apache. Demonstration on how to setup and configure NginX on Ubuntu server.

Enable HTTPS (HTTP+SSL) in NginX Web Server
Tutorial on enabling secure http connections for NginX web server. Demonstrating how to self sign your SSL certificate for the VPS server.

NginX Password Protect Web Directory
Helping you to protect specific web directories with passwords for restricting access to administration section or important private files that need to be accessed through the web.

Setup PHP-FPM with APC on Ubuntu 10.04 for Faster Performance
Installing and Configuring PHP5 with Fast CGI Process Manager along with the excellent op-code cache solution APC for faster and optimized PHP backend.

Setup MySQL with PHPMyAdmin on Ubuntu 10.04
Setting up MySQL database server and configuring for better performance in low memory environment. Also setup a web based database management front-end named PHPMyAdmin.

Configure Domains and Subdomains in your VPS Running NginX
Tutorial on DNS setup for adding additional domains and subdomains. Also configuring NginX for handling each domains/subdomains.

Domain Emails for Free Using Google Apps
Setup domain specific email addresses without installing any email server in your VPS. Google Apps seems to be a better solution in this regard.

Author: Masum
Tags: , ,

14 Comments + Add Comment

  • Lexi

    May 22, 2012 at 12:48 am

    Hi! Thank you for this tutorial. I’m trying to password protect a directory, originally following your instructions. But somehow I’m getting a 404 error, without being prompted to enter my username and password. I’ve moved my password file to /etc/nginx/ directory, because according to the error log, a username and pass could not be found. It’s still not working. Has something regarding the auth_basic module been updated since this tutorial has been posted? Thank in advance for any help; please let me know if you need to look into my configuration.

    • Masum

      May 22, 2012 at 8:53 am

      Hi,

      It should work wherever the passwd file is located. A similar configuration still works with my server. This is not an issue. Now as your config is not working, I think you need to post your nginx configuration here.

      Thanks

  • Lexi

    May 22, 2012 at 2:53 pm

    Hi! And thank you for the quick response. :) I do believe I’ve meddled too much with the code, but hopefully you can see what’s wrong with it.

    From /etc/nginx/sites-available/default:
    ——————————

    server
    {
    listen 80;
    server_name dev.alexandrialong.com;

    access_log /var/www/alexandrialong.com/logs/access.log;
    error_log /var/www/alexandrialong.com/logs/error.log;

    root /var/www/alexandrialong.com/public_html;

    error_page 401 /errorpages/401.html;
    error_page 403 /errorpages/403.html;
    error_page 404 /errorpages/404.html;
    error_page 500 502 503 504 /errorpages/500.html;

    location /
    {
    try_files $uri $uri/ /index.php?$args;
    }

    # rewrite adminpanel to use https
    location /adminpanel
    {
    rewrite ^/(.*) https://dev.alexandrialong.com/$1 permanent;
    }

    # Add trailing slash to */wp-admin requests. Needed if wordpress is installed later
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;

    # Directives to send expires headers
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$
    {
    expires 30d;
    }

    # Deny all attempts to access hidden files such as .htaccess, .htpasswd
    location ~ /\.
    {
    deny all;
    access_log off;
    log_not_found off;
    }

    location ~ \.php$
    {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:6000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/alexandrialong.com/public_html$fastcgi_script_name;
    }
    }

    #####
    # Expression Engine Configuration
    #####
    server
    {
    listen 80;
    server_name eedev.alexandrialong.com;
    root /var/www/eedev.alexandrialong.com;

    access_log /var/log/nginx/eedev.alexandrialong.com-access.log;
    error_log /var/log/nginx/eedev.alexandrialong.com-error.log info;

    location /
    {
    index index.php;
    try_files $uri $uri/ @ee;
    }

    location @ee
    {
    rewrite ^(.*) /index.php?$1 last;
    }

    location ~ \.php$
    {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:6000;
    fastcgi_index index.php5;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    }

    ######
    # Enable HTTPS
    #####
    server
    {
    listen 443;
    ssl on;
    ssl_certificate /usr/ssl/server.crt;
    ssl_certificate_key /usr/ssl/server.key;
    keepalive_timeout 70m;

    server_name dev.alexandrialong.com;

    access_log /var/www/alexandrialong.com/logs/access.log;
    error_log /var/www/alexandrialong.com/logs/error.log;

    root /var/www/alexandrialong.com/public_html;

    error_page 401 /errorpages/401.html;
    error_page 403 /errorpages/403.html;
    error_page 404 /errorpages/404.html;
    error_page 500 502 503 504 /errorpages/500.html;

    location /
    {
    try_files $uri $uri/ /index.php?$args;
    }

    # Add trailing slash to */wp-admin requests for wordpress
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;

    # Directives to send expires headers
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$
    {
    expires 30d;
    }

    # Deny all attempts to access hidden files such as .htaccess, .htpasswd
    location ~ /\.
    {
    deny all;
    access_log off;
    log_not_found off;
    }

    location ^~ /adminpanel/
    {
    auth_basic “Restricted”;
    auth_basic_user_file /conf.d/htpasswd;

    location ~ \.php$
    {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:6000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/alexandrialong.com/public_html$fastcgi_script_name;
    fastcgi_param HTTPS on;
    }
    }

    location ~ \.php$
    {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:6000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/alexandrialong.com/public_html$fastcgi_script_name;
    fastcgi_param HTTPS on;
    }

    }
    ———————-

    • Lexi

      May 22, 2012 at 2:55 pm

      D’oh! I meant to add that as a reply, I’m sorry.

    • Masum

      May 23, 2012 at 7:50 am

      Your config looks good, do you have the /var/www/alexandrialong.com/public_html/adminpanel/ directory created already and placed some files say “index.php” there for testing?

      • Lexi

        May 23, 2012 at 2:09 pm

        Yes, the directory is already set up with an “index.html” file inside.

        • Masum

          May 23, 2012 at 4:38 pm

          Hmmm, that’s interesting. If I’m not missing anything, then your configuration seems quite ok. Looks more like the problem lies somewhere else. Don’t take it otherwise, but did you check if the www-data user under which nginx runs has the necessary read permissions to the directory “adminpanel”? Also check if nginx has the read permission to the file htpasswd.

          Also don’t forget to restart nginx if any config changes are done, I often forget it myself :) Don’t know if this will solve your problem, but if you can figure out whats causing this, then please let me know.

          • Lexi

            May 23, 2012 at 8:57 pm

            I made sure that user “www-data” was the owner of /var/www and all subdirectories and files. It still didn’t work.

            However, when I moved the auth_basic and the htpasswd file path from “location ^~ /adminpanel/” to “location /” in the same HTTPS server block, my browsers prompted me for username and password. It works there, I can access my test index.html file in the root “public_html” directory. But when moving the lines of code back to their original position, I still get 404 when trying to access the index file in the “adminpanel” sub-directory.

            In the error log:
            ———————–

            2012/05/24 00:48:09 [error] 1416#0: *17 no user/password was provided for basic authentication, client: xxx.xxx.xxx.xxx, server: dev.alexandrialong.com, request: “GET /adminpanel/ HTTP/1.1″, host: “199.21.113.164″

            Do you know if anything else I should look at?

          • Masum

            May 24, 2012 at 9:14 am

            Though I’m not sure why this is not working, but you may try two alternative configurations to see if they work:

            1. Try replacing the location ^~ /adminpanel/ block to location /adminpanel then restart nginx

            2. Try replacing the location ^~ /adminpanel/ block to location ~ ^/adminpanel then restart nginx

            Thanks

          • Lexi

            May 27, 2012 at 6:49 pm

            Hi,

            I tried both of those, and neither worked, sadly. I tested password protection on the “/errorpages/” directory under the root “/public_html/” directory, and it works there, too. For some reason, the server just doesn’t want to protect the “/adminpanel/” directory. I’m not sure why the directory cannot be found when trying to access it from the web browser.

          • Masum

            May 28, 2012 at 6:28 am

            thats really interesting, can you try the commnad ls -All /var/www/public_html/adminpanel and post the result shown in your terminal?

          • Lexi

            May 29, 2012 at 4:03 am

            Hi, again!

            I had reinstalled by the time I saw your message, so sorry i won’t be able to provide to results to that. I resolved the issue by just starting over and making sure my Ubuntu’s install was up-to-date, which is something I believe i forgot to do in the first place (apt-get update). Not updating might have stopped something from installing correctly, and I didn’t catch the misfire in time. Thank you for all the help trying to troubleshoot the issue.

  • Antonio

    October 30, 2013 at 10:21 pm

    Hi! Thank you for this terrific tutorial. I need your help.
    I have the same problem than @Lexi but, unlike him, I can’t fix it. I have followed all your instructions in the post and the potential solutions given in the comments but I stuck.

    This is what I get when I execute ls -All to my adminpanel folder (/usr/share/nginx/www/myhostname/public_html/adminpanel)

    total 4
    -rw-r–r– 1 www-data root 245 oct 30 22:44 index.html

    Could you help me, please!!??
    Thank you in advance!

    PS: Sorry for my bad english!

  • Jeff

    April 25, 2014 at 3:51 am

    For any that may come across this in the future, I had the same problem as Lexi and Antonio. I found the problem/solution here:

    https://bbs.archlinux.org/viewtopic.php?id=179887

    Basically, in order for the browser to ask for credentials, it needs to receive a 401 from nginx. However, this tutorial never sets up the 401 page in the ‘errorpages’ directory, so instead it returns a 404 (not found), because it couldn’t find 401.html.

    The solution is to add a 401.html page to the errorpages directory. While you’re at it, it’s not a bad idea to add the rest, as well.

Leave a comment

Sponsored