Nginx
Nginx 是一个高性能的 HTTP 服务器和反向代理服务器,同时也支持 IMAP/POP3/SMTP 等协议。它以高并发、低资源消耗著称,广泛用于 Web 服务、负载均衡、静态资源托管等场景。
1.安装
bash
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL(使用 EPEL)
sudo yum install epel-release
sudo yum install nginx
# macOS(使用 Homebrew
brew install nginx2.启动与管理
bash
# 启动 Nginx
sudo systemctl start nginx
# 停止 Nginx
sudo systemctl stop nginx
# 重启 Nginx
sudo systemctl restart nginx
# 重载配置(不中断服务)
sudo systemctl reload nginx
# 检查状态
sudo systemctl status nginx
# 开机自启
sudo systemctl enable nginx在 macOS 上(非 systemd)可能需要直接运行 /usr/local/bin/nginx 或使用 brew services start nginx
3.基本配置文件结构
- 主配置文件通常位于
- Linux:
/etc/nginx/nginx.conf - macOS:
/usr/local/etc/nginx/nginx.conf
- Linux:
Nginx
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html; # 或 /var/www/html
index index.html index.htm;
}
}
}4.常用功能示例
1.托管静态网站
Nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
}然后将你的 HTML 文件放在 /var/www/my-site/ 目录下。
2.反向代理
将请求转发到后端应用(如 Node.js、Python Flask)
Nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000; # 转发到本地 3000 端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}3.负载均衡
Nginx
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}支持轮询(默认)、权重、IP 哈希等策略。
4.HTTPS 配置(需 SSL 证书)
为了启用 HTTPS,需要先获取 SSL 证书(可以免费从 Let's Encrypt 获取),并将证书文件配置到 Nginx。
Nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/fullchain.pem; # 证书文件路径
ssl_certificate_key /path/to/privkey.pem; # 私钥文件路径
location / {
root /var/www/my-site;
index index.html;
}
}
# 强制 HTTP 跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}测试与调试
bash
# 检查配置语法
sudo nginx -t
# 查看错误日志
tail -f /var/log/nginx/error.log
# 访问日志
tail -f /var/log/nginx/access.log命令速查
| 命令 | 说明 |
|---|---|
| 启动 nginx | 启动 Nginx 服务 |
| 停止 nginx -s stop | 停止 Nginx 服务 |
| 优雅停止 nginx -s quit | 优雅停止 Nginx 服务(等待当前请求处理完成) |
| 重载配置 nginx -s reload | 重新加载 Nginx 配置文件(不中断服务) |
| 重新打开日志文件 nginx -s reopen | 重新打开 Nginx 日志文件(用于日志滚动) |
其他常用配置
1.开启 Gzip 压缩
压缩响应内容可以显著减少传输大小,提高加载速度。
Nginx
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript;
}2.配置日志格式
自定义日志格式可以更方便地分析和监控 Nginx 运行。
Nginx
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;
}