Nginx 基础入门
2025/12/11大约 6 分钟
Nginx 基础入门
Nginx(发音为 "engine-x")是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。
什么是 Nginx
Nginx(发音为 "engine-x")是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。由俄罗斯程序员 Igor Sysoev 开发,于 2004 年首次公开发布。
主要特点
- 高性能:采用异步事件驱动架构,能够处理大量并发连接
- 低资源消耗:相比 Apache,占用更少的内存和 CPU
- 高可靠性:稳定性极高,可以 7×24 小时不间断运行
- 模块化设计:功能通过模块实现,易于扩展
主要应用场景
- Web 服务器:直接提供静态资源服务
- 反向代理:代理后端应用服务器
- 负载均衡:分发请求到多个后端服务器
- HTTP 缓存:缓存静态资源,减轻后端压力
安装 Nginx
Ubuntu/Debian 系统
# 更新软件包列表
sudo apt update
# 安装 Nginx
sudo apt install nginx -y
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 查看运行状态
sudo systemctl status nginxCentOS/RHEL 系统
# 安装 Nginx
sudo yum install nginx -y
# 或者使用 dnf(CentOS 8+)
sudo dnf install nginx -y
# 启动 Nginx
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx验证安装
安装完成后,在浏览器中访问服务器 IP 地址,如果看到 Nginx 欢迎页面,说明安装成功。
# 查看 Nginx 版本
nginx -v
# 查看详细版本和编译参数
nginx -VNginx 目录结构
主要目录(Ubuntu/Debian)
/etc/nginx/ # Nginx 配置目录
├── nginx.conf # 主配置文件
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 已启用站点配置(软链接)
├── conf.d/ # 其他配置文件
├── snippets/ # 配置片段
└── modules-enabled/ # 已启用的模块
/var/log/nginx/ # 日志目录
├── access.log # 访问日志
└── error.log # 错误日志
/var/www/html/ # 默认网站根目录
/usr/share/nginx/html/ # Nginx 默认页面主要目录(CentOS/RHEL)
/etc/nginx/ # Nginx 配置目录
├── nginx.conf # 主配置文件
└── conf.d/ # 配置文件目录
/var/log/nginx/ # 日志目录
/usr/share/nginx/html/ # 默认网站根目录基本配置
nginx.conf 主配置文件结构
# 全局块:影响整个 Nginx 服务器
user nginx;
worker_processes auto; # 工作进程数,auto 表示自动检测 CPU 核心数
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# events 块:影响 Nginx 服务器与用户的网络连接
events {
worker_connections 1024; # 每个进程的最大连接数
use epoll; # 使用 epoll 事件驱动模型
}
# http 块:配置最频繁的部分
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;
include /etc/nginx/sites-enabled/*;
}虚拟主机配置示例
创建配置文件 /etc/nginx/conf.d/example.conf:
server {
listen 80; # 监听端口
server_name example.com; # 域名
root /var/www/example; # 网站根目录
index index.html index.htm; # 默认首页
# 访问日志
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
# 静态文件处理
location / {
try_files $uri $uri/ =404;
}
# 错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}常用配置场景
1. 静态网站部署
server {
listen 80;
server_name static.example.com;
root /var/www/static;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}2. 反向代理
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:8080; # 后端服务地址
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;
}
}3. 负载均衡
upstream backend {
server 192.168.1.10:8080 weight=3; # 权重为 3
server 192.168.1.11:8080 weight=2; # 权重为 2
server 192.168.1.12:8080 backup; # 备用服务器
}
server {
listen 80;
server_name lb.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}4. HTTPS 配置
server {
listen 443 ssl http2;
server_name secure.example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /var/www/secure;
index index.html;
}
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name secure.example.com;
return 301 https://$server_name$request_uri;
}5. 限流配置
http {
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
listen 80;
server_name api.example.com;
location /api/ {
# 应用限流,允许 20 个突发请求
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
}常用命令
服务管理
# 启动 Nginx
sudo systemctl start nginx
# 停止 Nginx
sudo systemctl stop nginx
# 重启 Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx配置管理
# 测试配置文件语法
sudo nginx -t
# 测试配置并显示配置内容
sudo nginx -T
# 重新加载配置
sudo nginx -s reload
# 停止 Nginx
sudo nginx -s stop
# 优雅停止(处理完当前请求后停止)
sudo nginx -s quit日志管理
# 查看访问日志
sudo tail -f /var/log/nginx/access.log
# 查看错误日志
sudo tail -f /var/log/nginx/error.log
# 重新打开日志文件(日志轮转后使用)
sudo nginx -s reopenLocation 匹配规则
语法
location [ = | ~ | ~* | ^~ ] uri {
...
}优先级(从高到低)
=精确匹配^~前缀匹配(匹配成功后不再检查正则)~正则匹配(区分大小写)~*正则匹配(不区分大小写)- 无修饰符 前缀匹配
示例
# 精确匹配
location = / {
return 200 "exact match";
}
# 前缀匹配,优先级高于正则
location ^~ /static/ {
root /var/www;
}
# 正则匹配(区分大小写)
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
# 正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
expires 30d;
}
# 普通前缀匹配
location /api/ {
proxy_pass http://backend;
}常见问题排查
1. 端口被占用
# 查看 80 端口占用
sudo lsof -i :80
# 或
sudo netstat -tlnp | grep :802. 权限问题
# 检查文件权限
ls -la /var/www/html/
# 修改所有者
sudo chown -R nginx:nginx /var/www/html/
# 修改权限
sudo chmod -R 755 /var/www/html/3. SELinux 问题(CentOS/RHEL)
# 临时关闭 SELinux
sudo setenforce 0
# 永久关闭(需编辑配置文件)
sudo vi /etc/selinux/config
# 设置 SELINUX=disabled
# 或者设置 SELinux 策略
sudo setsebool -P httpd_can_network_connect 14. 防火墙设置
# Ubuntu/Debian (UFW)
sudo ufw allow 'Nginx Full'
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# CentOS/RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload性能优化建议
1. 工作进程优化
worker_processes auto; # 自动设置为 CPU 核心数
worker_rlimit_nofile 65535; # 每个进程最大文件打开数
events {
worker_connections 4096; # 每个进程最大连接数
use epoll; # 使用 epoll 模型
multi_accept on; # 一次接受多个连接
}2. 开启 Gzip 压缩
http {
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
}3. 缓存配置
http {
# 文件缓存
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}总结
Nginx 是一个功能强大且灵活的 Web 服务器和反向代理服务器。掌握其基本配置和常用功能,能够帮助你:
- ✅ 快速部署静态网站
- ✅ 搭建反向代理和负载均衡
- ✅ 配置 HTTPS 安全连接
- ✅ 实现请求限流和访问控制
- ✅ 优化网站性能
建议在学习过程中多实践,通过实际项目来加深理解。
