Skip to main content

Complete Guide to Installing and Configuring Nginx on Ubuntu

63 views 2 min read read

Learn how to install and configure Nginx on Ubuntu, including site setup, SSL configuration, security hardening, and performance optimization. A complete guide for system administrators and developers.

Installing Nginx

First, update your package list and install Nginx:

sudo apt update
sudo apt install nginx

Verifying Installation

After installation, check if Nginx is running:

sudo systemctl status nginx

Enable Nginx to start on boot:

sudo systemctl enable nginx

Basic Configuration

The main Nginx configuration file is located at /etc/nginx/nginx.conf . Site-specific configurations go in /etc/nginx/sites-available/ .

Creating a New Site Configuration

sudo nano /etc/nginx/sites-available/mysite

Basic server block configuration:

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;
    }
}

Enabling the Site

Create a symbolic link to enable the site:

sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Setting Up SSL with Let's Encrypt

Install Certbot for SSL certificates:

sudo apt install certbot python3-certbot-nginx

Obtain and install certificate:

sudo certbot --nginx -d example.com -d www.example.com

Let's Encrypt certificates expire after 90 days. To ensure your website remains secure, set up automatic renewal:

sudo certbot renew --dry-run # Test the renewal process
sudo systemctl status certbot.timer # Check if the renewal timer is active

Security Hardening

Add these security headers to your server block:

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000";

Optimizing Performance

Enable Gzip compression by adding to your configuration:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_min_length 1000;
gzip_comp_level 6;

Setting Up Caching

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

Monitoring Logs

Access logs are located at:

/var/log/nginx/access.log
/var/log/nginx/error.log

Monitor logs in real-time:

sudo tail -f /var/log/nginx/access.log

Related Posts