Nginx practical tutorial
What is Nginx?
Nginx (pronounced "engine-x") is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP proxy server. It is famous for its high stability, rich functions, and low system resource consumption. It is an indispensable component in the modern Web architecture.
Main features of Nginx:
- High Performance: Using asynchronous event-driven architecture, it can efficiently handle a large number of concurrent connections
- Low memory consumption: Compared with traditional Apache server, memory usage is greatly reduced
- High Stability: Stable operation with few failures
- Hot Deployment: Supports configuration upgrade without downtime
- Modular design: Has a rich third-party module ecosystem
- Reverse proxy: Provides powerful load balancing and proxy functions
1. Nginx installation and configuration
1.1 Ubuntu/Debian system installation
# 更新包列表
sudo apt update
# 安装Nginx
sudo apt install nginx
# 检查Nginx状态
sudo systemctl status nginx
# 启动Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
1.2 Docker installation
Installing Nginx using Docker is a great way to get started quickly, especially in a development environment:
# 拉取Nginx镜像
docker pull nginx:latest
# 运行Nginx容器
docker run -d \
--name my-nginx \
-p 80:80 \
-v $(pwd)/nginx.conf:/etc/nginx/nginx.conf \
-v $(pwd)/html:/usr/share/nginx/html \
nginx:latest
2. Nginx basic configuration
2.1 Main configuration file structure
The main configuration file for Nginx is located at/etc/nginx/nginx.conf, which controls the global behavior of Nginx:
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}
2.2 Server block configuration
Server Blocks are the way to configure virtual hosts in Nginx, allowing multiple websites to be hosted on one server:
# /etc/nginx/conf.d/default.conf
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /usr/share/nginx/html;
index index.html index.htm;
# 字符编码
charset utf-8;
# 主要位置配置
location / {
try_files $uri $uri/ =404;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
3. Reverse proxy configuration
3.1 Basic reverse proxy
Reverse proxy is one of the most commonly used features of Nginx, which forwards requests to the backend application server:
# 反向代理到后端应用服务器
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000; # 转发到本地运行的应用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
}
3.2 Load balancing configuration
When you have multiple backend servers, Nginx can act as a load balancer to distribute requests:
# 定义上游服务器组
upstream backend_app {
# 轮询(默认),可以添加权重
server 192.168.1.10:3000 weight=3;
server 192.168.1.11:3000 weight=2;
server 192.168.1.12:3000 weight=1;
# 也可以使用其他策略
# least_conn; # 最少连接
# ip_hash; # IP哈希,确保同一用户总是访问同一服务器
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
4. SSL/TLS configuration
4.1 Let's Encrypt SSL certificate configuration
Enabling HTTPS for your website is a basic requirement for modern web applications, and Let's Encrypt provides free SSL certificates:
# 安装Certbot
sudo apt install certbot python3-certbot-nginx
# 获取SSL证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期
sudo crontab -e
# 添加以下行
0 12 * * * /usr/bin/certbot renew --quiet
4.2 SSL configuration example
Certbot usually automatically configures Nginx after obtaining the certificate, but here is an example of manual configuration:
server {
listen 80;
server_name example.com www.example.com;
# 重定向HTTP到HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL证书配置
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS安全头部
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
root /usr/share/nginx/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
5. Cache configuration
5.1 Static resource cache
Properly configuring cache can significantly improve website performance and reduce server load:
# 静态资源缓存配置
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# 图片、视频、音频文件
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg|mp4|webm|ogg|mp3|wav)$ {
expires 1M;
add_header Cache-Control "public, immutable";
access_log off;
}
# CSS、JS文件
location ~* \.(css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json;
}
6. Security configuration
6.1 Basic security configuration
Ensuring Nginx security is an important part of operation and maintenance work. The following are some basic security configurations:
# 安全相关的头部设置
server {
listen 80;
server_name secure.example.com;
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;
# 防止MIME类型嗅探
add_header X-Content-Type-Options "nosniff" always;
# XSS防护
add_header X-XSS-Protection "1; mode=block" always;
# 隐藏Nginx版本
server_tokens off;
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ =404;
}
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
}
7. Best Practices
The following are some key configurations for Nginx performance optimization:
# 性能优化配置
worker_processes auto; # 自动设置为CPU核心数
worker_rlimit_nofile 65535; # 增加文件描述符限制
events {
worker_connections 4096; # 增加每个worker的连接数
use epoll; # 使用高效的事件模型
multi_accept on;
}
http {
# 基本性能设置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
# 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/javascript
application/javascript
application/json;
}
7.2 Deployment Best Practices
When deploying Nginx in a production environment, the following best practices should be followed:
- Configuration Backup: Back up the configuration before modifying it
- Configuration Test: Use
nginx -tTest whether the configuration is correct
- Smooth Restart: Use
nginx -s reloadSmooth restart to avoid service interruption
- Monitoring logs: Regularly check access logs and error logs
- Update and Maintenance: Keep Nginx version updated and fix security vulnerabilities
A simple deployment script example:
#!/bin/bash
# nginx_deployment.sh - Nginx部署脚本
# 配置备份
BACKUP_DIR="/etc/nginx/backups"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
echo "Backing up current configuration..."
cp -r /etc/nginx/nginx.conf $BACKUP_DIR/nginx.conf_$DATE
cp -r /etc/nginx/conf.d $BACKUP_DIR/conf.d_$DATE
# 验证配置
echo "Testing configuration..."
if nginx -t; then
echo "Configuration test passed"
# 平滑重启
echo "Reloading Nginx..."
nginx -s reload
echo "Deployment completed successfully"
else
echo "Configuration test failed"
exit 1
fi
Summarize
Nginx is a powerful, high-performance web server and reverse proxy server that plays an important role in modern web architecture. Through the installation, configuration, reverse proxy, load balancing, SSL configuration, etc. introduced in this article, you should be able to quickly get started with Nginx and apply it to actual projects.
In actual use, remember to adjust the configuration according to your specific needs and follow best practices to ensure system security and performance. As you gain experience, you can further explore Nginx's advanced features, such as more complex caching strategies, advanced security configurations, etc., to build a more powerful web application architecture.