Nginx on Localhost

Nginx (pronounced "engine-x") is a high-performance web server and reverse proxy. It's known for handling high traffic efficiently and is often used alongside or instead of Apache for serving static files, PHP applications, and as a load balancer.

Nginx default page: http://localhost

Nginx vs Apache

FeatureNginxApache
ArchitectureEvent-driven, asyncProcess/thread-based
Static filesExcellentGood
Memory usageLowHigher
PHP handlingVia PHP-FPMmod_php (easier)
.htaccess❌ No✅ Yes
Reverse proxyExcellentGood

Install Nginx

Ubuntu/Debian

sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

# Check status
sudo systemctl status nginx

# Test configuration
sudo nginx -t

macOS (Homebrew)

brew install nginx
brew services start nginx

# Config location: /usr/local/etc/nginx/

Windows

Download from nginx.org, extract, run nginx.exe

Basic Configuration

# /etc/nginx/sites-available/default
server {
    listen 80;
    server_name localhost;
    root /var/www/html;
    index index.html index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

PHP with Nginx (PHP-FPM)

# Install PHP-FPM
sudo apt install php-fpm

# Nginx config for PHP
server {
    listen 80;
    server_name localhost;
    root /var/www/html;
    index index.php index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }
}

Virtual Hosts

# /etc/nginx/sites-available/mysite
server {
    listen 80;
    server_name mysite.local;
    root /var/www/mysite;
    index index.html index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

# Enable site
sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# Add to /etc/hosts
127.0.0.1 mysite.local

Reverse Proxy (Node.js/React)

server {
    listen 80;
    server_name localhost;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Common Commands

# Start/stop/restart
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx  # Reload config without downtime

# Test configuration
sudo nginx -t

# View error logs
sudo tail -f /var/log/nginx/error.log

Troubleshooting

ProblemSolution
Port 80 in useStop Apache: sudo systemctl stop apache2
403 ForbiddenCheck file permissions and ownership
502 Bad GatewayPHP-FPM not running or wrong socket path
Config syntax errorRun nginx -t to find error