📥 安装与基本配置
安装 Nginx
bash
# Ubuntu/Debian
sudo apt update
sudo apt install -y nginx
# CentOS/RHEL
sudo yum install -y epel-release
sudo yum install -y nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 验证安装
nginx -v
nginx version: nginx/1.24.0
# 检查配置语法
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 访问测试(浏览器打开 http://服务器IP)
curl http://localhost
<!DOCTYPE html>
<html>
<head><title>Welcome to nginx!</title></head>
<body><h1>Welcome to nginx!</h1></body>
</html>Nginx 目录结构
text
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 自定义配置(推荐放这里)
│ └── default.conf
├── sites-available/ # 可用的站点配置
├── sites-enabled/ # 启用的站点配置(软链接)
├── mime.types # MIME 类型定义
└── modules-enabled/ # 动态模块配置文件结构
nginx
# main 全局块(影响整体运行)
worker_processes auto; # 工作进程数(auto = CPU 核数)
error_log /var/log/nginx/error.log warn;
# events 块(连接处理配置)
events {
worker_connections 1024; # 每个进程最大连接数
}
# http 块(HTTP 相关配置)
http {
include mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent';
# server 块(虚拟主机)
server {
listen 80; # 监听端口
server_name example.com; # 域名
# location 块(URL 匹配)
location / {
root /var/www/html; # 网站根目录
index index.html;
}
}
}📝 备注: 📝 结构层级:main → events → http → server → location,从大到小,层层嵌套。
常用管理命令
bash
# 测试配置语法
sudo nginx -t
# 重新加载配置(不中断服务,平滑过渡)
sudo nginx -s reload
# 快速停止(强制终止所有连接)
sudo nginx -s stop
# 优雅停止(处理完当前请求再停)
sudo nginx -s quit
# 查看 Nginx 进程
ps aux | grep nginx
root 12345 0.0 0.1 32768 1024 ? Ss 10:00 0:00 nginx: master process
www-data 12346 0.0 0.1 33792 2048 ? S 10:00 0:00 nginx: worker process