Administrator
发布于 2025-12-30 / 9 阅读
0

Rocky Linux 8/9 安装 Nginx(官方仓库 · Stable)

1. 环境说明

  • 操作系统:Rocky Linux 8 / 9

  • 安装来源:Nginx 官方 stable 仓库

  • 适用场景:个人服务器 / 生产环境

  • 优点:

    • 版本更新及时

    • 官方维护

    • 比系统自带版本更新


2. 添加 Nginx 官方仓库

创建仓库配置文件:

cat >/etc/yum.repos.d/nginx.repo <<'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=https://nginx.org/packages/rhel/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
EOF

说明:

  • $releasever

    • Rocky 8 → 8

    • Rocky 9 → 9

  • $basearch

    • 一般为 x86_64


3. 刷新缓存并安装 Nginx

dnf clean all
dnf makecache
dnf install -y nginx

4. 验证安装结果

查看版本

nginx -v

示例输出:

nginx version: nginx/1.26.x(可能版本更高)

查看安装来源(确认是官方仓库)

dnf info nginx

5. 启动并设置开机自启

systemctl start nginx
systemctl enable nginx

检查状态:

systemctl status nginx

6. 防火墙放行 HTTP / HTTPS

使用 firewalld

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

7. 目录结构说明(官方仓库)

/etc/nginx/
├── nginx.conf          # 主配置文件
├── conf.d/             # server 配置目录(推荐使用)
│   └── default.conf
├── mime.types

Web 根目录(默认):

/usr/share/nginx/html

日志目录:

/var/log/nginx/
├── access.log
└── error.log

8. 常用管理命令

nginx -t                 # 检查配置文件
systemctl reload nginx   # 平滑重载
systemctl restart nginx  # 重启
systemctl stop nginx     # 停止

9. 常见注意事项

9.1 不要使用系统自带 nginx

系统仓库版本通常较旧(如 1.20.x),建议:

dnf remove nginx

再使用官方仓库安装。


9.2 SELinux 注意事项(重要)

如果站点目录不在默认路径(如 /usr/local/blog):

chcon -R -t httpd_sys_content_t /your/web/root

临时关闭(仅用于排查):

setenforce 0

10. 最小 server 示例

server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

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

11. 最简单的https示例

upstream halo {
  server 127.0.0.1:8090;
}
server {
    listen 443 ssl;
	http2 on ;
    server_name xxx.xxx.cloud;

    ssl_certificate     /etc/key_nginx/blog.rzgcxy.cloud/xxx.xxx.cloud.pem;
    ssl_certificate_key /etc/key_nginx/blog.rzgcxy.cloud/xxx.xxx.cloud.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    access_log /var/log/nginx/xxx.xxx.cloud.access.log;
    error_log  /var/log/nginx/xxx.xxx.cloud.error.log warn;


    location / {
    proxy_pass http://halo;
    proxy_set_header HOST $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

12. 常用的示例

  • http转https示例

server {
    listen 80;
    server_name xxx.cloud *.xxx.cloud;
    return 301 https://$host$request_uri;
}
  • www域名转根域名示例

server {
    listen 443 ssl;
	http2 on;
    server_name www.xxx.cloud;

    ssl_certificate     /etc/key_nginx/www.rzgcxy.cloud/www.xxx.cloud.pem;
    ssl_certificate_key /etc/key_nginx/www.rzgcxy.cloud/www.xxx.cloud.key;

    return 301 https://xxx.cloud$request_uri;
}