How to setup a Nginx site on Ubuntu server
A Comprehensive Guide to Setting Up a New Site in Nginx
Table of contents
Introduction
Nginx is a powerful and efficient web server that can be used to serve static and dynamic content. Setting up a new site in Nginx involves creating a new server block configuration for the site, configuring the site settings, and enabling the site configuration. In this guide, we'll walk through the detailed steps to add a new site in Nginx on Ubuntu.
Step 1: Install Nginx
If Nginx is not already installed on your Ubuntu server, you can install it using the following commands:
sudo apt update
sudo apt install nginx
Step 2: Create a New Nginx Configuration File
Navigate to the Nginx sites-available
directory where you'll create a new configuration file for your site. Replace example.com
with your domain name or a unique identifier for your site:
sudo nano /etc/nginx/sites-available/example.com
Step 3: Configure Your Site in the Nginx Configuration File
Inside the configuration file, add the following configuration. Replace example.com
with your domain name and update the root
directive to point to the directory where your site's files are located:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
listen 80;
: Configures the server to listen on port 80, the default HTTP port.server_name
: Specifies the domain name(s) for your site.root
: Sets the root directory for your site's files.index
: Specifies the default file to serve when a directory is requested.location /
: Defines how Nginx should handle requests for the site's URLs.
Step 4: Create the Root Directory for Your Site
Create the root directory for your site and set the appropriate permissions:
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
Step 5: Enable Your Site Configuration
Create a symbolic link from the sites-available
directory to the sites-enabled
directory to enable your site configuration:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Step 6: Test Your Nginx Configuration
Before restarting Nginx, it's a good idea to test your configuration for syntax errors:
sudo nginx -t
If there are no syntax errors, you'll see a message like syntax is ok
followed by test is successful
.
Step 7: Restart Nginx
Once your configuration is correct, restart Nginx to apply the changes:
sudo systemctl restart nginx
Step 8: Verify Your Site
Open a web browser and navigate to your domain (e.g., http://example.com
). You should see the default Nginx welcome page or your website if you've already added content to it.