Nginx Configuration on VPS
Nginx is a popular open-source web server that can be used to serve static files, dynamic content, and proxy requests to other servers. It is known for its high performance, scalability, and security.
In this tutorial, we will learn how to install and configure Nginx on any VPS.
Prerequisites
Before installing Nginx, make sure you have the following prerequisites:
- A server with root access
- A domain name or IP address
- A web server that can be used to serve static files
Installing Nginx on Ubuntu
To install Nginx on Ubuntu, follow these steps:
-
Update the package index
Terminal window sudo apt update -
Install Nginx
Terminal window sudo apt install nginx -
Start and enable Nginx
Terminal window sudo systemctl start nginxsudo systemctl enable nginx -
Open your web browser and navigate to
http://your_server_ip. You should see the Nginx default welcome page.
Configuring Nginx on Ubuntu
-
Create a new server block configuration file
Terminal window sudo vim /etc/nginx/sites-available/defaultThis command opens the default configuration file for editing.
-
Replace the file content with the following content:
server {listen 80; # Listen on port 80, the default HTTP portserver_name localhost; # The server name, here it is set to localhostroot /var/www/html; # The root directory where files are served fromindex index.html index.htm; # The default files to servelocation / {try_files $uri $uri/ =404; # Try to serve the requested URI, if not found return a 404}} -
Create the document root directory if it doesn’t exist
Terminal window sudo mkdir -p /var/www/html -
Change ownership of the document root directory to the current user
Terminal window sudo chown -R $USER:$USER /var/www/html -
Set the permissions for the document root directory
Terminal window sudo chmod -R 755 /var/www/html -
Create the directory for the web root.
Terminal window cd /var/www/htmlThis command navigates to the web root directory.
-
Create an empty index.html file
Terminal window touch index.htmlThis command creates an empty index.html file.
-
Open the index.html file for editing
Terminal window sudo vim index.htmlThis command opens the index.html file for editing.
-
Add the following content to the index.html file:
<html><head><title>Welcome to Nginx</title></head><body><h1>Hello, world!</h1></body></html> -
Test the Nginx configuration
Terminal window sudo nginx -tThis command tests the Nginx configuration for syntax errors.
-
Reload Nginx to apply the changes
Terminal window sudo systemctl reload nginxThis command reloads the Nginx service to apply the changes.
-
Open your web browser and navigate to
URL_ADDRESS_server_ip. You should see the Nginx default welcome page.
Summary
In this tutorial, we learned how to install and configure Nginx to serve static files.
Start your journey with ChaiCode
All of our courses are available on chaicode.com. Feel free to check them out.