5.4 Web服务基础与Nginx使用

5.4 Nginx Web 服务基础与常用管理

Nginx 简介

Nginx 是一款高性能 Web 服务器和反向代理服务器,广泛应用于网站部署、API 转发、负载均衡和 HTTPS 服务场景。

主要特点:

  • 高并发处理能力
  • 低资源占用
  • 配置简单灵活
  • 支持反向代理与负载均衡
  • 支持 HTTPS 与静态资源加速

常见应用场景:

  • 静态网站部署
  • Web 应用反向代理
  • API 网关
  • HTTPS 证书接入
  • 负载均衡集群

安装与部署

CentOS / Rocky Linux

1
2
3
4
yum install nginx -y

# 或
dnf install nginx -y

Ubuntu / Debian

1
2
apt update
apt install nginx -y

查看版本:

1
nginx -v

服务管理

启动服务:

1
systemctl start nginx

停止服务:

1
systemctl stop nginx

重启服务:

1
systemctl restart nginx

重载配置:

1
systemctl reload nginx

设置开机自启:

1
systemctl enable nginx

查看状态:

1
systemctl status nginx

核心目录结构

路径 说明
/etc/nginx/nginx.conf 主配置文件
/etc/nginx/conf.d/ 虚拟主机配置目录
/usr/share/nginx/html/ 默认网站根目录
/var/log/nginx/ 日志目录

检查配置语法:

1
nginx -t

重新加载配置:

1
nginx -s reload

Web 服务访问配置

开放 HTTP 服务:

1
2
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

开放 HTTPS 服务:

1
2
firewall-cmd --add-service=https --permanent
firewall-cmd --reload

查看监听端口:

1
ss -tunlp | grep nginx

验证服务:

1
curl http://localhost

简单站点部署

创建测试页面:

1
2
3
cat > /usr/share/nginx/html/index.html <<EOF
<h1>Hello Nginx</h1>
EOF

浏览器访问:

1
http://服务器IP

如果页面正常显示,说明站点部署成功。

反向代理基础

将访问请求转发到后端服务:

1
2
3
4
5
6
7
8
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://127.0.0.1:8080;
}
}

常用于:

  • Java 应用
  • Python 应用
  • PHP-FPM
  • Node.js 服务

修改后执行:

1
2
nginx -t
systemctl reload nginx

日志管理

访问日志:

1
tail -f /var/log/nginx/access.log

错误日志:

1
tail -f /var/log/nginx/error.log

统计访问量:

1
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

常见故障排查

服务未启动:

1
systemctl status nginx

配置错误:

1
nginx -t

端口未监听:

1
ss -tunlp | grep 80

查看错误日志:

1
tail -100 /var/log/nginx/error.log

云服务器环境还需确认:

  • 系统防火墙已放行
  • 云安全组已开放对应端口
  • 域名解析配置正确

总结

Nginx 是 Linux 平台最常用的 Web 服务组件,其核心能力包括:

  • Web 网站托管
  • 静态资源服务
  • 反向代理
  • HTTPS 加密访问
  • 负载均衡

掌握 Nginx 的安装、配置、日志分析和故障排查,是 Linux 运维与网站部署的基础能力。


5.4 Web服务基础与Nginx使用
https://blog.sh462li.top/2026/05/28/Linux_learn/5.4 Web服务基础与Nginx使用/
作者
SHAO
发布于
2026年5月28日
许可协议