跳转到内容

CentOS 8 安装 OpenResty 详细教程

项目要求
操作系统CentOS 8 (x86_64)
内存>= 1 GB
权限root 或 sudo

# 安装 yum-utils(提供 yum-config-manager)
dnf install -y yum-utils
# 添加 OpenResty 官方 CentOS 8 仓库
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

dnf install -y openresty openresty-resty openresty-opm
包名说明
openresty核心主程序
openresty-restyresty 命令行工具
openresty-opmOpenResty 包管理器

/usr/local/openresty/
├── nginx/
│ ├── conf/
│ │ ├── nginx.conf # 主配置文件
│ │ └── conf.d/ # 站点配置目录(需手动创建)
│ ├── html/ # 默认网站根目录
│ └── logs/ # 日志目录
├── lualib/ # 内置 Lua 库
└── bin/
└── openresty # 可执行文件(软链至 nginx)

mkdir -p /usr/local/openresty/nginx/conf/conf.d
vi /usr/local/openresty/nginx/conf/nginx.conf

http {} 块末尾、} 之前添加一行,引入站点配置:

http {
# ... 原有内容保持不变 ...
include conf.d/*.conf;
}
cat > /usr/local/openresty/nginx/conf/conf.d/default.conf << 'EOF'
server {
listen 80;
server_name _;
location / {
default_type text/plain;
content_by_lua_block {
ngx.say("OpenResty is running.")
}
}
# 静态文件服务示例
location /static/ {
root /usr/local/openresty/nginx/html;
}
# 反向代理示例(按需启用)
# location /api/ {
# proxy_pass http://127.0.0.1:8080/;
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# }
}
EOF
/usr/local/openresty/bin/openresty -t

输出 syntax is oktest is successful 即正常。


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

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

# 验证版本
/usr/local/openresty/bin/openresty -v
# 本机访问测试
curl http://127.0.0.1

期望输出:OpenResty is running.


以下为将 / 路径代理至后端服务的完整示例:

cat > /usr/local/openresty/nginx/conf/conf.d/proxy.conf << 'EOF'
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
server {
listen 80;
server_name example.com;
client_max_body_size 100m;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
}
}
EOF
# 重载配置
systemctl reload openresty

# 启动 / 停止 / 重启 / 重载(不中断连接)
systemctl start openresty
systemctl stop openresty
systemctl restart openresty
systemctl reload openresty
# 手动方式(等效)
/usr/local/openresty/bin/openresty -s reload
/usr/local/openresty/bin/openresty -s stop
# 查看实时访问日志
tail -f /usr/local/openresty/nginx/logs/access.log
# 查看错误日志
tail -f /usr/local/openresty/nginx/logs/error.log

问题原因解决方法
dnf 找不到 openresty 包官方源未添加成功重新执行第一节,检查 repo 文件是否生成
80 端口无法访问防火墙未放行执行第六节开放端口
nginx.conf 语法错误配置有误运行 openresty -t 查看具体行号
启动失败报端口占用其他进程占用 80ss -tlnp | grep :80 查找并处理冲突进程
include conf.d/*.conf 无效目录不存在执行 4.1 节创建目录

© 2025-2026 LiuXing. All Rights Reserved.