Optimizing Your Ubuntu 22.04 VPS and Nginx for Performance

Introduction

Now that we’ve set up a secure Nginx web server on our low-end Ubuntu 22.04 VPS, it’s time to optimize it for better performance. This guide will cover key tweaks to enhance speed and efficiency.

Step 1: Enable Gzip and Brotli Compression

Compression reduces bandwidth usage and improves load times for users.

Enable Gzip Compression

Edit your Nginx configuration:

sudo nano /etc/nginx/nginx.conf

Add the following inside the http block:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
gzip_min_length 1000;
gzip_proxied any;
gzip_comp_level 5;

Restart Nginx:

sudo systemctl reload nginx

Step 2: Enable HTTP/3 for Faster Connections

HTTP/3 improves latency and connection reliability, especially on mobile networks.

Install Nginx with HTTP/3 Support

sudo add-apt-repository ppa:ondrej/nginx -y
sudo apt update
sudo apt install nginx -y

Modify your Nginx configuration:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    listen 443 quic reuseport;
    listen [::]:443 quic reuseport;
    
    http3 on;
    add_header Alt-Svc 'h3=":443"; ma=86400';
}

Restart Nginx:

sudo systemctl reload nginx

Step 3: Optimize Nginx Worker Processes and Buffers

Adjust Worker Processes and Connections

Determine the number of available CPU cores:

grep -c ^processor /proc/cpuinfo

Set worker processes accordingly in /etc/nginx/nginx.conf:

worker_processes auto;
worker_connections 1024;

Restart Nginx:

sudo systemctl reload nginx

Optimize Buffer Sizes

Add these settings to reduce resource overhead:

client_body_buffer_size 128k;
client_max_body_size 10M;
client_header_buffer_size 64k;
large_client_header_buffers 4 64k;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;

Step 4: Prevent Clickjacking and XSS Attacks

add_header X-Frame-Options DENY;
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;

Conclusion

With these optimizations, your VPS will be more efficient and performant. In the next post, we’ll look at setting up automated backups and monitoring. Stay tuned! 🚀