top of page

Posts

Implementing Basic Authentication with Nginx



In the previous article, I talked about configuring basic authentication using Apache and mentioned my intention to explore it with Nginx as well. Therefore, in this article, I will delve into configuring basic authentication with Nginx. As usual, I will use Vagrant to walk us through the installation of Nginx, configuring Virtualhost, and implementing basic authentication. I encourage you to read until the end.

Environment and version

  • VirtualBox Version 6.1

  • Vagrant Version 2.2.19

  • CentOS/7

  • Nginx Version nginx/1.23.1

Goal and Procedures

Goal

The goal of this blog is to apply basic authentication to a virtual host page configured with nginx.

Setup procedures

  1. Edit the vagrantfile and start up Vagrant.

  2. Access to the server using vagrant ssh.

  3. Install Nginx.

  4. Set up Virtualhost.

  5. Implement basic authentication.


I will roughly follow the above steps, and it is ok to skip the parts you already know!

Log in to the virtual server launched with Vagrant using SSH

To proceed with vagrant ssh, here I will implement the same configurations as I used for applying basic authentication with Apache.


Edit the vagrantfile to enable internet connectivity within the local environment.


An example of a vagrantfile configuration is as follows.


What is absolutely necessary for the connection is:


1| config.vm.network "private_network", ip: "192.168.43.20"   


 1| # -*- mode: ruby -*-

 2|  # vi: set ft=ruby :

 3|

 4|  # All Vagrant configuration is done below. The "2" in Vagrant.configure

 5|  # configures the configuration version (we support older styles for

 6|  # backwards compatibility). Please don't change it unless you know what

 7|  # you're doing.

 8|   Vagrant.configure("2") do |config|

 9|

10|  # Every Vagrant development environment requires a box. You can search for

12|   config.vm.box = "centos/7"

13| 

14|  # Create a forwarded port mapping which allows access to a specific port

15|  # within the machine from a port on the host machine. In the example below,

16|  # accessing "localhost:8080" will access port 80 on the guest machine.

17|  # NOTE: This will enable public access to the opened port

18|   config.vm.network "forwarded_port", guest: 80, host: 8080

19| 

20|  # Create a private network, which allows host-only access to the machine

21|  # using a specific IP.

22|   config.vm.network "private_network", ip: "192.168.43.20"

23| 

24|  end


After editing is completed, execute vagrant up.


1| vagrant up


Once done, connect to the virtual server using vagrant ssh, and as you might have guessed, the processes for configuring basic authentication with Apache from the previous article are exactly the same. I thought it would be better to have it here, and I would be very happy if you would go through with it.


1| vagrant ssh


Once you've successfully logged in, you are good to go. Next, let's install Nginx.

Install Nginx

When I installed Apache last time, I could simply go ahead and install httpd without much thought. However, that is not the case for Nginx. If you try to install it without proper setup, it won’t work as it will tell you that there is no such thing. So, before diving into the installation process, let's go through some preparation.


  • I will assume that yum update has already been performed. 


Now, let's start by creating a repository for Nginx.


1| sudo vi /etc/yum.repos.d/nginx.repo


Now that you can open nginx.repo, write the following settings in the editor.


1| [nginx]

2| name=nginx repo

4| gpgcheck=0

5| enabled=1


After configuration is completed as above, save it with :wq.


Now, let's install Nginx.


1| sudo yum install nginx


This completes the installation. If there are no issues, let's proceed to start Nginx up.


1| sudo systemctl start nginx


Finally, enter http://localhost:8080 in your browser. Once you see the usual Nginx welcome page displayed as shown below, it confirms the successful installation and startup of Nginx.





Next, let's create a Virtualhost.

Create a Virtualhost (a little bit complicated)

The first step is to create a document root for the virtual host. (Note: "Virtualhost" is sometimes abbreviated as "vhost.")


*Since I am using CentOS this time, "sites-available" and "sites-enabled" directories do not exist by default and need to be created. Otherwise, if you're using a Debian-based OS, there's no need to create them since these directories already exist as per Apache’s convention.


1| mkdir -p /var/www/vhosts/example.com/public_html


Once the creation is completed, navigate to public_html, and proceed to create an index.html file.


1| sudo vi index.html


Feel free to add any content you'd like, then type :wq to save and exit.


In Nginx, configuring a Virtualhost (vhost) requires creating directories named "sites-available" and "sites-enabled", where configuration files will be stored. Later, symbolic links will be used to link these directories. Let's start by creating these two directories.


1| mkdir /etc/nginx/sites-available


And one more:


1| mkdir /etc/nginx/sites-enabled


After creating the two directories, I will proceed to create configuration files for Virtualhost.


Given that the domain for this setup is example.com, we will name the file as example.com.conf.


The configuration will be as follows:


1| server {

2|  listen 80;

3|  servername example.com;

4|  location / {

5|    root/var/www/vhosts/example.com/public_html;

6|     index index.html index.php;

7|  }

8| }


After completing the above configuration, save it by typing :wq. Then, proceed to set up symbolic links from the "sites-available" directory to the "sites-enabled" directory.


sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf


To ensure that Nginx loads the above settings, I will add some directives to the nginx.conf file. The content to be added is as follows:


 1| include /etc/nginx/sites-enabled/*;


This should be added at the bottom of the nginx.conf file.


 1| user nginx;

 2| worker_processes 1;

 3|  

 4| error_log /var/log/nginx/error.log warn;

 5| pid /var/run/nginx.pid;

 6| 

 7| events {

 8|   worker_connections 1024;

 9| }

10|

11| http {

12|    include /etc/nginx/mime.types;

13|    default_type application/octet-stream;

14|    log_format main '$remote_addr - $remote_user [$time_local] 1| "$request" '

15|                    '$status $body_bytes_sent "$http_referer" '

16|                    '"$http_user_agent" "$http_x_forwarded_for"';

17|    access_log /var/log/nginx/access.log main;

18|  

19|    sendfile on;

20|    #tcp_nopush on;

21|    keepalive_timeout 65;

22|  

23|    #gzip on;

24|    include /etc/nginx/sites-enabled/*; #added part

25|    include /etc/nginx/conf.d/*.conf;

26| }


After completing the above configuration, I will perform a syntax check.


1| nginx -t


And don’t forget to edit the hosts file.


1| any IP address example.com


Append above to the hosts file and save it.


* Settings won't be reflected unless executed with administrator privileges. Therefore, make sure to run Notepad or any text editor as an administrator, and then open the hosts file.


With this setup, if you search for http://example.com in your browser and see the content specified during setup, the configuration is completed.


Now that the virtualhost has been set up, the last step is to set up basic authentication.

Apply basic authentication to the configured vhost

When using Apache, ht-related tools are automatically installed, ensuring smooth operation. However, in the case of nginx, these tools are not included by default, rendering the htpasswd command unusable. Therefore, I will begin by installing them first.


1| sudo yum install httpd-tools


After completing the installation, I will use the htpasswd command to prepare for basic authentication.


1| htpasswd -c /var/www/vhosts/example.com/.htpasswd usernamen 


Register a username and password.


Just to be sure, double check that the username and password are properly created.


1| cat /var/www/vhosts/example.com/.htpasswd


Once the configured username and hash value are displayed, it confirms that the setup has been done correctly. 


Finally, to apply basic authentication, I will add auth_basic and auth_basic_user_file directives to example.com.conf.


 1| server {

 2|  listen 80;

 3|  servername example.com;

 4|  location / {

 5|     root /var/www/vhosts/example.com/public_html;

 6|     index index.html index.php;

 7|     auth_basic auth_nginx_test;

 8|     auth_basic_user_file /var/www/vhosts/example.com/.htpasswd;

 9|  }

10|}


Once these configurations are added, restart Nginx. Upon successful application of basic authentication, users will be prompted for a username and password. 


With these steps, the setup of the basic authentication on Nginx is completed.

This blog post is translated from a blog post written by Ken on our Japanese website Beyond Co..


Recent Posts

See All

Commentaires


bottom of page