CentOS 7.6 安装 Nginx 搭建网站的步骤是什么?

在 CentOS 7.6 上安装 Nginx 并搭建网站的步骤如下:

一、安装 Nginx

1. 添加 EPEL 仓库

sudo yum install epel-release -y

2. 安装 Nginx

sudo yum install nginx -y

3. 启动并设置开机自启

sudo systemctl start nginx
sudo systemctl enable nginx

4. 检查防火墙

# 如果防火墙开启,添加 HTTP 和 HTTPS 服务
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

二、配置网站

1. 创建网站目录

sudo mkdir -p /var/www/yourdomain.com/html
sudo chown -R nginx:nginx /var/www/yourdomain.com
sudo chmod -R 755 /var/www/yourdomain.com

2. 创建测试页面

sudo vi /var/www/yourdomain.com/html/index.html

内容示例:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Your Site</title>
</head>
<body>
    <h1>Success! Your site is working.</h1>
</body>
</html>

3. 创建 Nginx 配置文件

sudo vi /etc/nginx/conf.d/yourdomain.com.conf

内容示例:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    root /var/www/yourdomain.com/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

4. 测试配置并重启 Nginx

# 测试配置文件语法
sudo nginx -t

# 重启 Nginx
sudo systemctl restart nginx

三、高级配置(可选)

1. 配置 SSL(使用 Let’s Encrypt)

# 安装 Certbot
sudo yum install certbot python2-certbot-nginx -y

# 获取 SSL 证书
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

2. 配置 PHP(如果需要)

# 安装 PHP-FPM
sudo yum install php-fpm php-mysql -y

# 启动 PHP-FPM
sudo systemctl start php-fpm
sudo systemctl enable php-fpm

# 修改 Nginx 配置支持 PHP

在 server 块中添加:

location ~ .php$ {
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

四、验证安装

  1. 检查 Nginx 状态

    sudo systemctl status nginx
  2. 访问测试

    • 浏览器访问 http://your_server_ip
    • http://yourdomain.com
  3. 查看日志

    sudo tail -f /var/log/nginx/access.log
    sudo tail -f /var/log/nginx/error.log

五、常用管理命令

# 启动/停止/重启 Nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx  # 平滑重载配置

# 查看状态
sudo systemctl status nginx

# 测试配置
sudo nginx -t

注意事项:

  1. yourdomain.com 替换为你的实际域名
  2. 如果没有域名,可以使用服务器 IP 地址
  3. 确保域名已正确解析到服务器 IP
  4. 定期更新系统和 Nginx:sudo yum update nginx
  5. 建议配置 SELinux 或将其设置为宽容模式(测试环境)

这样就完成了在 CentOS 7.6 上安装 Nginx 并搭建网站的基本步骤。

云服务器