Welcome to your first foray into Nginx! In this section, we'll build a foundational Nginx configuration that allows you to serve a simple static website. Think of this as the digital equivalent of setting up your storefront. We'll start with the absolute essentials and gradually introduce key concepts.
Every Nginx installation comes with a default configuration file, often located at /etc/nginx/nginx.conf. However, for managing individual sites, it's best practice to create separate configuration files within a dedicated directory, typically /etc/nginx/sites-available/ and then symlink them to /etc/nginx/sites-enabled/. This keeps things organized and makes it easy to enable or disable sites.
Let's create our first configuration file. We'll name it mysite.conf.
sudo nano /etc/nginx/sites-available/mysite.confNow, paste the following basic configuration into this file. We'll break down each part.
server {
listen 80;
server_name example.com www.example.com;
root /var/www/mysite;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}Let's dissect this configuration block by block:
server { ... }: This is the fundamental block in Nginx. It defines a virtual server and is responsible for handling requests for a specific domain or IP address.
listen 80;: This directive tells Nginx to listen for incoming connections on port 80, which is the standard port for HTTP traffic. If you were setting up HTTPS, you'd also seelisten 443 ssl;here.
server_name example.com www.example.com;: This directive specifies the domain names that thisserverblock should respond to. When a client requestsexample.comorwww.example.com, Nginx will use this configuration to handle the request. You should replaceexample.comwith your actual domain name.