Nginx安装配置完整教程,从安装到运行
时间:2026-10-5 07:52 作者:emer 分类: 无
前言
刚装好 CentOS 服务器,想跑个网站,第一步就是装 Nginx。Nginx 是目前最流行的 Web 服务器,性能高、占用资源少,还能做反向代理和负载均衡。本文就从安装 Nginx 开始,一步步讲怎么配置一个能跑的网站。
第一步:安装 Nginx
1. 安装 EPEL 源
CentOS7 默认源里的 Nginx 版本比较老,先装 EPEL 源:
yum install epel-release -y
2. 安装 Nginx
yum install nginx -y
3. 启动 Nginx
systemctl start nginx
4. 设置开机自启
systemctl enable nginx
5. 开放防火墙
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
6. 测试
浏览器访问你的服务器 IP,应该能看到 Nginx 默认欢迎页面。
第二步:Nginx 配置文件结构
Nginx 的配置文件都在 /etc/nginx/ 目录下:
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 子配置文件目录
│ └── default.conf # 默认站点配置
├── fastcgi.conf
├── mime.types
└── ...
一般我们写站点配置,都放在 conf.d/ 目录下,每个站点一个文件。
第三步:配置第一个站点
1. 创建网站根目录
mkdir -p /var/www/html/test
2. 写一个测试页面
echo "Hello Nginx" > /var/www/html/test/index.html
3. 创建站点配置文件
vi /etc/nginx/conf.d/test.conf
写入:
server {
listen 80;
server_name www.example.com;
root /var/www/html/test;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
4. 检查配置是否正确
nginx -t
输出 test is successful 就是没问题。
5. 重新加载 Nginx
systemctl reload nginx
6. 测试
浏览器访问 www.example.com,应该能看到 "Hello Nginx"。
注意: 要把域名解析到你服务器的 IP 上,或者在本地 hosts 文件里加一条记录。
常用配置说明
listen 监听端口
listen 80;
监听 80 端口,HTTP 默认端口。
如果要监听 HTTPS 的 443 端口:
listen 443 ssl;
server_name 域名
server_name www.example.com example.com;
可以写多个域名,用空格隔开。
root 网站根目录
root /var/www/html/test;
网站文件放在这个目录下。
index 默认首页
index index.html index.htm;
用户访问网站根目录的时候,默认找哪个文件。
配置 PHP 支持
如果要跑 PHP 网站,还需要配置 PHP-FPM。
1. 安装 PHP-FPM
yum install php-fpm php-mysql -y
2. 启动 PHP-FPM
systemctl start php-fpm
systemctl enable php-fpm
3. 修改 Nginx 配置
在站点配置里加上 PHP 支持:
server {
listen 80;
server_name www.example.com;
root /var/www/html/test;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
4. 重启 Nginx
systemctl restart nginx
5. 测试 PHP
创建一个 info.php 文件:
echo "<?php phpinfo(); ?>" > /var/www/html/test/info.php
浏览器访问 www.example.com/info.php,应该能看到 PHP 信息页面。
常见坑
坑1:403 Forbidden
访问网站报 403,一般是权限问题。
排查:
- 看文件权限是不是 644,目录是不是 755
- 看所有者是不是 nginx
- 看 SELinux 是不是开着
chown -R nginx:nginx /var/www/html/test
chmod -R 755 /var/www/html/test
坑2:502 Bad Gateway
访问网站报 502,说明 Nginx 连不上 PHP-FPM。
排查:
- 看 PHP-FPM 有没有启动:
systemctl status php-fpm - 看配置里的
fastcgi_pass地址对不对
坑3:配置改完不生效
改了 Nginx 配置,没 reload,结果配置没生效。
解决: 改完配置记得 reload:
nginx -t
systemctl reload nginx
坑4:域名解析了还是打不开
域名解析了,但还是打不开。
排查:
- 看防火墙有没有开 80 端口
- 看安全组有没有开 80 端口(云服务器)
- 看域名解析有没有生效:
ping www.example.com
总结
Nginx 安装配置的完整流程:
- 安装 Nginx:
yum install nginx -y - 启动并开机自启:
systemctl start nginx && systemctl enable nginx - 开放防火墙:80 和 443 端口
- 写站点配置:在
conf.d/下创建配置文件 - 检查并重载:
nginx -t && systemctl reload nginx
Nginx 是 Web 服务器的入门必备,装完这个就能跑网站了。
遇到问题加QQ23979811 协助处理