欢迎光临
我们一直在努力

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

一、前言

Nginx 高性能、低占用,主流 Web 反向代理 / 静态资源服务,部署分yum 在线安装、源码编译安装两种;虚拟主机实现一台服务器绑定多个域名、部署多个网站,是运维日常高频配置。本文从安装→配置文件详解→虚拟主机三种方式→防火墙放行全套实操。


二、Nginx 两种安装方式

方式 1:YUM 一键安装(生产快速部署首选)

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-port=80/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 虚拟主机三种实现方式

环境:一台服务器,两个站点

站点 A:www.a.com 网页目录 /data/www/a

站点 B:www.b.com 网页目录 /data/www/b

bash

运行

# 提前创建站点目录与首页
mkdir -p /data/www/a /data/www/b
echo "site A" > /data/www/a/index.html
echo "site B" > /data/www/b/index.html

1、基于域名(企业最常用,推荐)

不同域名、同一个 IP、同一个 80 端口,靠 Host 区分站点

新建 /etc/nginx/conf.d/vhost.conf

nginx

server {
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\\hosts;Linux:/etc/hosts)

plaintext

服务器IP www.a.com
服务器IP www.b.com

重载 nginx,分别访问域名打开对应网站。

2、基于端口(内网测试多用)

同一域名、同一 IP、不同端口区分站点

nginx

server {
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-port=8081-8082/tcp
firewall-cmd –reload

访问:IP:8081、IP:8082

3、基于 IP(极少使用,需多网卡多公网 IP)

不同 IP,相同端口,各自绑定站点。


六、常用运维命令汇总

bash

运行

nginx -t #配置语法检查
systemctl reload nginx #平滑重载配置(不中断业务)
systemctl stop nginx #停止服务
tail -f /var/log/nginx/access.log #实时看访问日志


七、生产规范总结

  • 所有站点配置统一放到conf.d/*.conf,主配置只做全局配置;
  • 上线前必nginx -t校验,避免配置错误导致服务宕机;
  • 虚拟主机优先使用域名区分,是企业建站标准方案。
  • 赞(0)
    未经允许不得转载:171主机测评 » Nginx 安装、基础配置、多站点虚拟主机实战(CentOS7/8 通用)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址