How to Install Nginx on Ubuntu 22.04 and Configure

How to Install Nginx on Ubuntu 22.04 and Configure. In this post, we show you what is Nginx, its features, advantages then the install phase.

So, shall we start with how to Install Nginx on Ubuntu 22.04 and Configure.

What is Nginx?

Image Source: YouTube

Nginx is a web server that you use as a reverse proxy, load balancer, and HTTP cache. Known for its high performance, stability, and low resource consumption. The world’s busiest websites, including Airbnb, Box, Dropbox, and Netflix use Nginx.

It is written in C language and has a reputation for being lightweight and efficient. The software is often used as an alternative to the Apache web server, especially in high traffic environments, where performance is critical. In addition to serving static and dynamic web content, Nginx is used to serve video and audio streaming, and to proxy requests to other servers.

In addition, Nginx acts as a load balancer, distributing incoming traffic across multiple servers to improve the scalability and reliability of a system. Also configures the HTTP cache to reduce the load on the application servers and improve the performance of the system. Overall, Nginx is a powerful and flexible tool for serving web content and handling traffic on the internet.

Features of Nginx

Some of the crucial features of Nginx include:

  • Reverse Proxy – Nginx acts as a reverse proxy, routing traffic from the internet to one or more servers running applications or services.
  • Load balancing – distributes incoming traffic across multiple servers, improving the scalability and reliability of a system.
  • HTTP cachecaches static content and dynamically generated content, reducing the load on the application servers and improving the performance of the system.
  • SSL/TLS termination – handles SSL/TLS encryption and decryption, offloading this resource intensive process from the application servers.
  • Virtual hosting – hosts multiple websites on a single server, using a technique called “virtual hosting.”
  • FastCGI support – works with FastCGI servers, allowing it to serve dynamic content using scripting languages such as PHP.
  • HTTP/2 support – supports the HTTP/2 protocol, which allows for faster and more efficient transfer of web content.
  • Rewriting and redirection – rewrites URLs and redirects traffic, making it easy to modify the behaviour of a web server without changing the underlying application code.
  • Access controls – Nginx can be configured to allow or deny access to specific resources based on the IP address, hostname, or other criteria.

Advantages of Nginx

There are several advantages to using Nginx as a web server or reverse proxy:

  • Performance: Nginx is known for its high performance and ability to handle a large number of concurrent connections. After all, it is designed to be lightweight and efficient, using a small amount of memory and CPU resources.
  • Stability: Nginx is known for its stability and reliability, even under heavy loads. It has a reputation for being able to run uninterrupted for extended periods without crashing or experiencing other issues.
  • Low resource consumption: Nginx is designed to be resource efficient, using a small amount of memory and CPU resources. This makes it well suited for use on servers with limited resources or in high traffic environments where performance is critical.
  • Flexibility: Nginx is used as a web server, reverse proxy, load balancer, and HTTP cache. Well, it is also extended through the use of third party modules. This allows it to be customized to fit a wide variety of use cases.
  • Simplicity: Nginx has a straightforward configuration syntax and a small footprint, making it easy to set up and maintain.
  • Community support: Nginx has a large and active community of users and developers, making it easy to find help and resources when needed.

How to Install Nginx on Ubuntu 22.04 and Configure

Follow this step by step instructions to install and configure Nginx on Ubuntu 22.04.

Prerequisites

  • An Ubuntu 22.04 server is installed on your system.
  • A root user or a user with sudo privileges.

Step 1 - Install Nginx

By default, the Nginx web server package is included in the Ubuntu default repository. So you can easily install it via the APT command.

				
					apt install nginx -y
				
			

Once the Nginx server is installed, you verify the Nginx installation using the following command:

				
					nginx -version
				
			

You should see the Nginx version in the following output.

				
					nginx version: nginx/1.23.2
				
			

By default, the Nginx server listens on port 80. You can check it with the following command.

				
					ss -antpl | grep nginx
				
			

You should see the following output.

				
					LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=15438,fd=6),("nginx",pid=15437,fd=6),("nginx",pid=15435,fd=6))
				
			

Now, verify the Nginx server using the curl command.

				
					curl -4 http://localhost
				
			

You should see the Nginx test page in the following output.

				
					<!DOCTYPE html>
<html>

<p>Welcome to nginx!</p>
<style></style>

<body>
<h2>Welcome to nginx!</h2>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script></body>
</html>

				
			

At this point, the Nginx web server is installed on your server. You can now proceed to configure the UFW firewall.

Step 2 - Configure UFW Firewall

Next, you will need to allow Nginx ports through the UFW firewall application. Basically, you list all available UFW application profiles using the following command:

				
					ufw app list
				
			

You should see all application profiles in the following output.

				
					Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH

				
			

Now, enable the Nginx HTTP application profile using the following command.

				
					ufw allow 'Nginx HTTP'
				
			

Next, you can check the status of the UFW firewall with the following command.

				
					ufw status
				
			

You should see all active UFW rules in the following output.

				
					Status: active

To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)

				
			

At this point, the UFW firewall is configured to allow Nginx service. Please proceed to manage Nginx service.

Step 3 - Manage Nginx Service

By default, the Nginx service is managed by systemd. Besides, you easily manage it with systemctl command line tool. First, let’s check the active status of the Nginx service using the following command.

				
					systemctl status nginx
				
			

You should see the Nginx status in the following output.

				
					● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/etc/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2023-01-08 21:11:27 IST; 12h ago
Docs: man:nginx(8)
Main PID: 15435 (nginx)
Tasks: 3 (limit: 4915)
CGroup: /system.slice/nginx.service
├─15435 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
├─15437 nginx: worker process
└─15438 nginx: worker process

Jan 08 21:11:19 vyompc systemd[1]: Starting A high performance web server and a reverse proxy server...
Jan 08 21:11:27 vyompc systemd[1]: Started A high performance web server and a reverse proxy server.

				
			

To restart the Nginx status, run the following command.

				
					systemctl restart nginx
				
			

You can stop the Nginx service with the following command.

				
					systemctl stop nginx
				
			

To disable the Nginx service, run the following command.

				
					systemctl disable nginx
				
			

If you want to re enable the Nginx service, run the following command.

				
					systemctl enable nginx
				
			

Step 4 - Create Nginx Virtual Host

Virtual hosting is an Nginx feature that allows you to host multiple websites on a single server. By default, Nginx virtual host is configured to serve the /var/www/html directory.

Let’s create a new website directory using the following command.

				
					mkdir /var/www/html/website
				
			

Next, change the ownership of the website directory to www-data:

				
					chown -R www-data:www-data /var/www/html/website
				
			

Then, create a simple HTML file inside the website directory.

				
					nano /var/www/html/website/index.html
				
			

Add the following code:

				
					<html>
<h2>Welcome to Nginx!</h2>
<body>
<h3>Congratulations! Your virtual hosting is working</h3>
</body>
</html>
				
			

Save and close the file when you are done.

Next, you need to create a new Nginx virtual host configuration file to serve the above website content. You create it inside the Nginx configuration directory.

				
					nano /etc/nginx/conf.d/website.conf
				
			

Define the path of your website as shown below:

				
					server {
listen 80;
server_name website.example.com;
root /var/www/html/website;
index index.html;

server_name your_domain www.your_domain;

location / {
try_files $uri $uri/ =404;
}
}

				
			

Save and close the file when you are done. Then, verify the Nginx configuration for any syntax error with the following command.

				
					nginx -t
				
			

You should see the following output.

				
					nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
				
			

Sometimes, you will get a hash bucket memory error after creating a new virtual host. To resolve this error, edit the Nginx default configuration file.

				
					nano /etc/nginx/nginx.conf
				
			

Add the following line below the line http {:

				
					server_names_hash_bucket_size 64;
				
			

Save and close the file then restart the Nginx service to apply the changes.

				
					systemctl restart nginx
				
			

Step 5 - Verify Nginx Virtual Host

At this point, the Nginx web server is installed and configured. Now, open your web browser and type the URL http://website.example.com to access your new website. If everything is fine, you should see your website page on the following screen.

Thank you for reading How to Install Nginx on Ubuntu 22.04 and Configure. Let us conclude the article now. 

How to Install Nginx on Ubuntu 22.04 and Configure Conclusion

In this post, we explained how to install the Nginx web server on Ubuntu 22.04. We also explained how to manage the Nginx service and create an Nginx virtual host. I hope this guide will help you to use Nginx in the production environment to host multiple websites. Lastly, Nginx includes built in security features such as SSL/TLS termination and access controls. Finally, it can also be configured to work with third party security solutions such as web application firewalls.

In order to explore more of our Nginx content, please navigate to this section of our blog

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

1 2 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x