Nginx Configuration: Building Fast Web Servers

Nginx is a high-performance web server and reverse proxy. Its event-driven architecture makes it ideal for serving static content and load balancing.

## Why Nginx?

- Handles thousands of concurrent connections
- Low memory usage
- Reverse proxy and load balancing
- SSL/TLS termination
- Static file serving

## Basic Configuration

```nginx
server {
   listen 80;
   server_name example.com;

   root /var/www/html;
   index index.html;

   location / {
       try_files $uri $uri/ =404;
   }

   location /api/ {
       proxy_pass http://localhost:3000;
   }

   # Static files with caching
   location ~* \.(css|js|png|jpg|jpeg)$ {
       expires 1y;
       add_header Cache-Control "public";
   }
}
```

## SSL Configuration

```nginx
server {
   listen 443 ssl http2;
   server_name example.com;

   ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

   # Security headers
   add_header X-Frame-Options DENY;
   add_header X-Content-Type-Options nosniff;
}
```

## Load Balancing

```nginx
upstream backend {
   server 10.0.0.1:3000;
   server 10.0.0.2:3000;
   server 10.0.0.3:3000 backup;
}

server {
   location / {
       proxy_pass http://backend;
   }
}
```

## Rate Limiting

```nginx
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

location /api/ {
   limit_req zone=api burst=20;
   proxy_pass http://backend;
}
```

## Gzip Compression

```nginx
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
```

## Conclusion

Nginx excels at serving web traffic at scale. Master reverse proxy, SSL, and load balancing for production-ready deployments.

评论
暂无评论