Installing and Configuring Nginx
Nginx is a high-performance web server and reverse proxy widely used for serving websites and web applications.
Install Nginx
Ubuntu/Debian:
apt update
apt install nginx -y
systemctl enable nginx
systemctl start nginx
CentOS/AlmaLinux/Rocky:
dnf install nginx -y
systemctl enable nginx
systemctl start nginx
Test the Installation
Open your browser and navigate to http://YOUR_SERVER_IP. You should see the Nginx welcome page.
Configuration Structure (Ubuntu)
/etc/nginx/nginx.conf— main config/etc/nginx/sites-available/— site configs (inactive until enabled)/etc/nginx/sites-enabled/— symlinks to active site configs
Create a Server Block for Your Domain
nano /etc/nginx/sites-available/yourdomain.com
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
root /var/www/yourdomain.com;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Enable the site and reload:
ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx
Useful Commands
nginx -t # Test configuration for errors
systemctl reload nginx # Apply changes without downtime
systemctl restart nginx