Rocky Linux 上安装和配置 Nginx

前提条件

  • Rocky Linux 8 或更高版本
  • root 权限或 sudo 权限
  • 可用的互联网连接

安装步骤

1. 添加 Nginx 官方源

首先需要添加 Nginx 的官方源,以确保获取最新版本:

sudo yum install epel-release -y # 安装 epel 源    
sudo yum makecache # 更新 yum 缓存

2. 安装 Nginx

sudo yum install nginx -y # 安装 Nginx
sudo nginx -v # 查看 Nginx 版本

3. 管理 Nginx 服务

sudo systemctl start nginx # 启动 Nginx
sudo systemctl enable nginx # 设置开机自启   
sudo systemctl status nginx # 查看Nginx状态

4. 配置防火墙

防火墙开放 80443 端口。

sudo firewall-cmd --permanent --add-service=http # 开放80端口
sudo firewall-cmd --permanent --add-service=https # 开放443端口(如需配置HTTPS)
sudo firewall-cmd --reload # 重载防火墙配置

Nginx 配置

1. 主要配置文件位置

  • 主配置文件:/etc/nginx/nginx.conf
  • 网站配置目录:/etc/nginx/conf.d/
  • 默认网站目录:/usr/share/nginx/html/
  • 日志文件目录:/var/log/nginx/

2. 创建网站配置

# 创建新的配置文件
sudo vim /etc/nginx/conf.d/mysite.conf
server {
    listen 80;
    server_name example.com;
    root /var/www/mysite;
    
    access_log /var/log/nginx/mysite_access.log;
    error_log /var/log/nginx/mysite_error.log;

    location / {
        index index.html index.htm;
    }
}

3. 测试和重载配置

# 测试配置是否正确
nginx -t

# 重载配置
systemctl reload nginx

常用维护命令

systemctl stop nginx # 停止 Nginx

systemctl restart nginx # 重启 Nginx

tail -f /var/log/nginx/error.log # 查看错误日志

tail -f /var/log/nginx/access.log # 查看访问日志

性能优化

  1. 开启 Gzip 压缩
    gzip on; # 开启 Gzip 压缩
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; # 压缩特定类型的响应
    gzip_min_length 1000; # 仅压缩大于 1000 字节的响应
    
  2. 配置缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { # 匹配静态资源
        expires 30d;  # 设置缓存过期时间为 30 天
        add_header Cache-Control "public, no-transform"; # 添加 Cache-Control 头部
    }
    

安全配置

  1. 隐藏 Nginx 版本信息
    server_tokens off; # 隐藏 Nginx 版本信息,增加安全性
    
  2. 配置 SSL/HTTPS
    server {
        listen 443 ssl;
        server_name example.com;
        
        ssl_certificate /path/to/cert.pem;
        ssl_certificate_key /path/to/key.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
    }
    

故障排除

常见问题及解决方案:

  1. 无法启动 Nginx
    • 检查端口占用:netstat -tulpn | grep :80
    • 查看错误日志:journalctl -u nginx.service
  2. 403 Forbidden 错误
    • 检查目录权限:ls -la /var/www/mysite
    • 检查 SELinux 状态:sestatus
  3. 502 Bad Gateway
    • 检查后端服务是否运行
    • 检查 upstream 配置