CentOS 7 安装 Nginx 并配置自启服务
更新时间: 2025/9/23 | 总字数: 0 字 | 阅读时长: 0 分钟
前言
梳理了两种常用的 Nginx 安装方式,差异对比如下,可根据需求自行选择。
| 安装方式 | 优点 | 缺点 |
|---|---|---|
| yum 安装 | 1. 傻瓜式在线安装,无需额外配置 2. 自动安装所需依赖环境 3. 升级简单,无需考虑系统兼容性问题 | 1. 软件版本落后 2. 安装过程无法干预 3. 不能自定义安装路径及功能模块 4. 多主机安装不能保证软件版本一致 |
| 源码编译安装 | 1. 按需编译,灵活度比较高 2. 可自定义编译路径及功能模块 3. 多主机编译安装版本一致 | 1. 编译、安装、配置、部署复杂 2. 需自行解决依赖关系并安装 3. 升级难度大,需考虑系统兼容性问题 |
① yum 安装 推荐
安装工具
sudo yum install yum-utils配置存储库
存储库配置说明
通过存储库安装有两种方式:
① 从默认的 RHEL 或 CentOS 仓库安装 Nginx,虽然简单便捷,但提供软件包版本较旧。执行如下命令即可安装 Epel 存储库。
sudo yum install epel-release② 从 nginx.org 官方仓库安装 Nginx,只需配置一次 yum 仓库,此后提供的包始终是最新的,下文针对此种方式进行示例说明。
创建存储库文件
创建并编辑 yum 存储库文件。
sudo vi /etc/yum.repos.d/nginx.repo添加配置内容
进入 insert 模式,添加如下配置内容,:wq 保存退出。
[nginx-stable]
name=nginx stable
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true切换存储库(按需)
默认使用稳定 Nginx 软件包的存储库。如果想使用主线 Nginx 软件包,运行以下命令切换:
sudo yum-config-manager --enable nginx-mainline重建缓存
重建缓存,将包信息缓存到本地。
sudo yum clean all
sudo yum makecache fast更新软件
sudo yum -y update安装 Nginx
安装若提示接受 GPG 密钥,验证是否匹配 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 ,若匹配选择接受,耐心等待安装完成。
# 在线安装 Nginx
sudo yum install -y nginx
# 查看版本信息
sudo nginx -v
# 打印如下,说明安装成功。
nginx version: nginx/1.24.0启动 Nginx
service nginx start访问页面响应如下说明启动成功 !

② 源码编译安装
依赖准备
先决条件
源码安装需要准备如下环境:
- gcc:用于
Nginx源码编译。 - pcre:
Nginx的rewrite和HTTP模块用于正则匹配支持。 - zlib:开发人员压缩算法,提供
Nginx各种模块需要使用的gzip和deflate压缩。 - openssl:为
Nginx提供https协议支持。 - jemalloc:用于优化内存管理。
安装所需依赖
sudo yum install -y gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel jemalloc jemalloc-devel创建用户和组
# 创建组
groupadd www
# 创建用户
useradd -g www -M -s /sbin/nologin www下载源码
官网下载地址:https://nginx.org/en/download.html ,以稳定版本 nginx-1.24.0 为例。
# 下载 Nginx 源码包
curl -O https://nginx.org/download/nginx-1.24.0.tar.gz
# 解压文件
tar -zxvf nginx-1.24.0.tar.gz
# 拷贝到 /usr/local/nginx 目录下
mv nginx-1.24.0 /usr/local/nginx
# 进入源码目录
cd nginx-1.24.0编译安装
进行编译安装,若安装过程报错,可按照提示安装相应依赖,也可按需调整配置项。
常用配置项参数整理及说明:
| 参数 | 说明 |
|---|---|
| --help | 打印帮助信息 |
| –prefix=path | 编译安装目录,默认为 /usr/local/nginx |
| --sbin-path=path | 可执行文件目录,默认为 prefix/sbin/nginx |
| --modules-path=path | 动态模块目录,默认为 prefix/modules |
| --conf-path=path | 配置文件目录,默认为 prefix/conf/nginx.conf |
| --error-log-path=path | 错误日志文件目录,默认为 prefix/logs/error.log |
| --pid-path=path | 进程 ID 文件所在目录,默认为 prefix/logs/nginx.pid |
| –user=name | 设置非特权用户名称,默认 nobody |
| –group=name | 设置工作进程组名称,默认为非特权用户名称 |
| --with-http_stub_status_module | 启用基本状态信息访问 |
| --with-http_sub_module | 启用通过指定字符替换修改响应 |
| --with-http_v2_module | 启用对 HTTP/2 的支持 |
| --with-http_ssl_module | 启用 SSL 支持 |
| --with-stream | 启用通用代理和负载均衡的流模块 |
| --with-stream_ssl_preread_module | 启用从ClientHello消息提取信息 |
| --with-stream_ssl_module | 启用流模块 SSL 支持 |
| --with-http_gzip_static_module | 启用发送预压缩文件支持 |
| --with-http_realip_module | 启用标头字段中地址发送 |
| --with-http_flv_module | 启用 flv 流媒体支持 |
| --with-http_mp4_module | 启用 MP4 支持 |
| --with-openssl=path | 设置 openssl 库源的路径 |
| --with-pcre=path | 设置 PCRE 库源的路径 |
| --with-pcre-jit | 构建具有"即时编译" 支持的 PCRE库 |
| --with-compat | 启用动态模块兼容性 |
| --with-debug | 启用调试日志 |
| --with-file-aio | 允许使用异步文件 I/O |
| --with-http_addition_module | 启用在响应前后添加文本 |
| --with-http_auth_request_module | 启用根据子请求结果实现客户端授权 |
| --with-http_dav_module | 启用通过 webdav 协议提供文件管理自动化 |
| --with-http_gunzip_module | 为不支持 "gzip" 编码方法的客户端解压缩使用 |
| --with-http_image_filter_module=dynamic | 允许转换图像 |
| --with-http_slice_module | 将请求拆分为子请求,提供更有效的大响应缓存 |
| --with-http_xslt_module=dynamic | 允许使用一个或者多个 XSLT 样式表转换 XML 响应 |
| --with-mail=dynamic | 启用邮件代理服务器 |
| --with-mail_ssl_module | 启用邮件代理服务器 SSL 支持 |
| --with-threads | 允许启用线程池 |
| --with-cc-opt=parameters | 设置添加到 CFLAGS 变量的附加参数 |
| --with-ld-opt=parameters | 设置链接期间使用的附加参数 |
更多配置项可通过如下命令查看,或参考:从源代码构建 Nginx 。
./configure --help | more# 进行模块配置(预编译自检)
./configure --prefix=/usr/local/nginx \
--user=www \
--group=www \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_v2_module \
--with-http_ssl_module \
--with-stream \
--with-threads \
--with-stream_ssl_preread_module \
--with-stream_ssl_module \
--with-http_auth_request_module \
--with-http_gzip_static_module \
--with-http_gunzip_module \
--with-http_realip_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-openssl=/root/openssl-3.2.1 \
--with-pcre=/root/pcre-8.45 \
--with-zlib=/root/zlib-1.3.1 \
--with-pcre-jit \
--with-ld-opt=-ljemalloc
# 编译安装
make && make install配置服务
使用 vim 编辑器,打开 /lib/systemd/system/nginx.service 配置文件。
vim /usr/lib/systemd/system/nginx.service添加如下配置,注意路径是否与安装位置一致。
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPost=/bin/sleep 0.1
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
TimeoutStartSec=120
LimitNOFILE=1000000
LimitNPROC=1000000
LimitCORE=1000000
[Install]
WantedBy=multi-user.target设置开机自启
systemctl enable nginx优化 Nginx 配置
备份默认 nginx.conf 配置文件。
mv /usr/local/nginx/conf/nginx.conf{,_bk}替换 nginx.conf 配置文件。
配置内容参考如下:
user www www;
worker_processes auto;
error_log /data/wwwlogs/error_nginx.log crit;
pid /var/run/nginx.pid;
worker_rlimit_nofile 51200;
events {
use epoll;
worker_connections 51200;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 1024m;
client_body_buffer_size 10m;
sendfile on;
tcp_nopush on;
keepalive_timeout 120;
server_tokens off;
tcp_nodelay on;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_intercept_errors on;
#Gzip Compression
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
gzip_types
text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
text/javascript application/javascript application/x-javascript
text/x-json application/json application/x-web-app-manifest+json
text/css text/plain text/x-component
font/opentype application/x-font-ttf application/vnd.ms-fontobject
image/x-icon;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
##Brotli Compression
#brotli on;
#brotli_comp_level 6;
#brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
##If you have a lot of static files to serve through Nginx then caching of the files' metadata (not the actual files' contents) can save some latency.
#open_file_cache max=1000 inactive=20s;
#open_file_cache_valid 30s;
#open_file_cache_min_uses 2;
#open_file_cache_errors on;
log_format json escape=json '{"@timestamp":"$time_iso8601",'
'"server_addr":"$server_addr",'
'"remote_addr":"$remote_addr",'
'"scheme":"$scheme",'
'"request_method":"$request_method",'
'"request_uri": "$request_uri",'
'"request_length": "$request_length",'
'"uri": "$uri", '
'"request_time":$request_time,'
'"body_bytes_sent":$body_bytes_sent,'
'"bytes_sent":$bytes_sent,'
'"status":"$status",'
'"upstream_time":"$upstream_response_time",'
'"upstream_host":"$upstream_addr",'
'"upstream_status":"$upstream_status",'
'"host":"$host",'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
######################## default ############################
server {
listen 80;
server_name _;
access_log /data/wwwlogs/access_nginx.log combined;
root /data/wwwroot/default;
index index.html index.htm index.php;
#error_page 404 /404.html;
#error_page 502 /502.html;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
location ~ [^/]\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
location ~ ^/(\.user.ini|\.ht|\.git|\.svn|\.project|LICENSE|README.md) {
deny all;
}
location /.well-known {
allow all;
}
}
########################## vhost #############################
include vhost/*.conf;
}curl -L "https://s3.dodoo.co/config/nginx.conf" -o /usr/local/nginx/conf/nginx.conf配置环境变量
编辑 profile 文件,按 i 进入 insert 模式。
vi /etc/profile配置 nginx 环境变量,将 /usr/local/nginx/sbin 添加至如下位置,:wq 保存退出。
unset i
unset -f pathmunge
# 在文件尾行增加如下配置:
export PATH=/usr/local/nginx/sbin:$PATH 重新加载环境变量并验证。
# 重新加载环境变量
source /etc/profile
# 查看版本,验证是否安装配置成功
nginx -v
# 打印如下,说明安装以及环境变量配置成功
nginx version: nginx/1.24.0启动 Nginx
# 启动 Nginx
systemctl start nginx访问页面响应如下说明启动成功 !
