Nginx 安装、基础配置、多站点虚拟主机实战(CentOS7/8 通用)

发布时间:2026/6/4 0:05:13

Nginx 安装、基础配置、多站点虚拟主机实战(CentOS7/8 通用) 一、前言Nginx 高性能、低占用主流 Web 反向代理 / 静态资源服务部署分yum 在线安装、源码编译安装两种虚拟主机实现一台服务器绑定多个域名、部署多个网站是运维日常高频配置。本文从安装→配置文件详解→虚拟主机三种方式→防火墙放行全套实操。二、Nginx 两种安装方式方式 1YUM 一键安装生产快速部署首选bash运行# 安装epel源 yum install epel-release -y # 安装nginx yum install nginx -y # 启停、开机自启 systemctl start nginx systemctl enable nginx systemctl status nginx默认目录汇总必记主配置文件/etc/nginx/nginx.conf子配置目录/etc/nginx/conf.d/推荐站点配置放此处默认网站根目录/usr/share/nginx/html日志目录/var/log/nginx/access.log 访问日志、error.log 错误日志方式 2源码编译安装自定义版本、自定义路径bash运行# 安装编译依赖 yum install gcc gcc-c make pcre-devel zlib-devel openssl-devel -y wget http://nginx.org/download/nginx-1.24.0.tar.gz tar -zxf nginx-1.24.0.tar.gz cd nginx-1.24.0 # 指定安装路径 ./configure --prefix/usr/local/nginx make make install # 启停 /usr/local/nginx/sbin/nginx #启动 /usr/local/nginx/sbin/nginx -s stop #停止 /usr/local/nginx/sbin/nginx -s reload #重载配置三、防火墙放行 80 端口bash运行firewall-cmd --permanent --add-port80/tcp firewall-cmd --reload浏览器访问服务器 IP出现 Nginx 默认页面即安装成功。四、nginx.conf 主配置文件结构拆解nginx#全局块运行用户、进程数 user nginx; worker_processes auto; #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 ; sendfile on; keepalive_timeout 65; # 导入conf.d下所有conf站点配置规范写法不要全写在主配置 include /etc/nginx/conf.d/*.conf; }配置修改后校验语法nginx -t重载生效nginx -s reload五、Nginx 虚拟主机三种实现方式环境一台服务器两个站点站点 Awww.a.com网页目录/data/www/a站点 Bwww.b.com网页目录/data/www/bbash运行# 提前创建站点目录与首页 mkdir -p /data/www/a /data/www/b echo site A /data/www/a/index.html echo site B /data/www/b/index.html1、基于域名企业最常用推荐不同域名、同一个 IP、同一个 80 端口靠 Host 区分站点新建/etc/nginx/conf.d/vhost.confnginxserver { listen 80; server_name www.a.com a.com; root /data/www/a; index index.html index.htm; } server { listen 80; server_name www.b.com b.com; root /data/www/b; index index.html index.htm; }本地 host 测试Windows:C:\Windows\System32\drivers\etc\hostsLinux:/etc/hostsplaintext服务器IP www.a.com 服务器IP www.b.com重载 nginx分别访问域名打开对应网站。2、基于端口内网测试多用同一域名、同一 IP、不同端口区分站点nginxserver { listen 8081; server_name www.test.com; root /data/www/a; } server { listen 8082; server_name www.test.com; root /data/www/b; }放行端口bash运行firewall-cmd --permanent --add-port8081-8082/tcp firewall-cmd --reload访问IP:8081、IP:80823、基于 IP极少使用需多网卡多公网 IP不同 IP相同端口各自绑定站点。六、常用运维命令汇总bash运行nginx -t #配置语法检查 systemctl reload nginx #平滑重载配置不中断业务 systemctl stop nginx #停止服务 tail -f /var/log/nginx/access.log #实时看访问日志七、生产规范总结所有站点配置统一放到conf.d/*.conf主配置只做全局配置上线前必nginx -t校验避免配置错误导致服务宕机虚拟主机优先使用域名区分是企业建站标准方案。

相关新闻