{T}

编译安装和命令行命令

编译安装

前置环境

需要内核为 Linux 2.6 及以上版本的操作系统,因为 Linux 2.6 及以上内核才支持 epoll,而在 Linux 上使用 select 或 poll 来解决事件的多路复用,是无法解决高并发压力问题的

bash
uname -a

前置环境安装:

  • GCC (GNU Compiler Collection) 用来编译 C 语言程序。Nginx 不会直接提供二进制可执行程序(1.2.x 版本中已经开始提供某些操作系统上的二进制安装包,但通过直接编译源代码进行的需要安装)
  • PCRE(Perl Compatible Regular Expressions,Perl 兼容正则表达式)是由 Philip Hazel 开发的函数库,目前为很多软件所使用,该库支持正则表达式。如果在配置文件 nginx.conf 里使用正则表达式,那么在编译 Nginx 时就必须把 PCRE 库编译进 Nginx,因为 Nginx 的 HTTP 模块要靠它来解析正则表达式
  • zlib 库用于对 HTTP 包的内容做 gzip 格式的压缩,如果在 nginx.conf 里配置 gzip on,并指定对于某些类型 (content-type) 的 HTTP 响应使用 gzip 来进行压缩以减少网络传输量,那么在编译时就必须把 zlib 编译进 Nginx
  • OpenSSL 如果服务器不只是要支持 HTTP,还需要在更安全的 SSL 协议上传输 HTTP,那么就需要拥有 OpenSSL。另外,如果想使用 MD5、SHA1 等散列函数,那么也需要安装它
bash
yum install -y gcc
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel

磁盘目录

要使用 Nginx,还需要在 Linux 文件系统上准备以下目录

  • Nginx 源代码存放目录。该目录用于放置从官网上下载的 Nginx 源码文件,以及第三方或自己所写的模块源代码文件
  • Nginx 编译阶段产生的中间文件存放目录。该目录用于放置在 configure 命令执行后所生成的源文件及目录,以及 make 命令执行后生成的目标文件和最终连接成功的二进制文件。默认情况下,configure 命令会将该目录命名为 objs,并放在 Nginx 源代码目录下
  • 部署目录。该目录存放实际 Nginx 服务运行期间所需要的二进制文件、配置文件等。默认情况下,该目录为 /usr/local/nginx
  • 日志文件存放目录。日志文件通常会比较大,当研究 Nginx 的底层架构时,需要打开 debug 级别的日志,这个级别的日志非常详细,会导致日志文件的大小增长得极快,需要预先分配一个拥有更大磁盘空间的目录

Linux 内核参数的优化

由于默认的 Linux 内核参数考虑的是最通用的场景,这明显不符合用于支持高并发访问的 Web 服务器的定义,所以需要修改 Linux 内核参数,使得 Nginx 可以拥有更高的性能。

当 Nginx 作为静态 Web 内容服务器、反向代理服务器或是提供图片缩略图功能的服务器时,其内核参数的调整都是不同的。这里只针对最通用的、使 Nginx 支持更多并发请求的 TCP 网络参数做简单说明。需要修改 /etc/sysctl.conf 来更改内核参数。例如最常用的配置:

bash
fs.file-max = 999999
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.ip_local_port_range = 1024    61000
net.ipv4.tcp_rmem = 4096 32768 262142
net.ipv4.tcp_wmem = 4096 32768 262142
net.core.netdev_max_backlog = 8096
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog=1024

执行命令:

bash
# 备份原配置文件
sudo cp /etc/sysctl.conf /etc/sysctl.conf.bak.$(date +%Y%m%d_%H%M%S)
 
# 创建新的 sysctl.conf 文件
cat << 'EOF' | sudo tee /etc/sysctl.conf
fs.file-max = 999999
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.ip_local_port_range = 1024 61000
net.ipv4.tcp_rmem = 4096 32768 262142
net.ipv4.tcp_wmem = 4096 32768 262142
net.core.netdev_max_backlog = 8096
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 1024
EOF
 
# 应用配置
sudo sysctl -p

参数解释:

  • file-max:这个参数表示进程(比如一个 worker 进程)可以同时打开的最大句柄数,这个参数直接限制最大并发连接数,需根据实际情况配置
  • tcp_tw_reuse:这个参数设置为 1,表示允许将 TIME-WAIT 状态的 socket 重新用于新的 TCP 连接,这对于服务器来说很有意义,因为服务器上总会有大量 TIME-WAIT 状态的连接
  • tcp_keepalive_time:参数表示当 keepalive 启用时,TCP 发送 keepalive 消息的频度。默认是 2 小时,若将其设置得小一些,可以更快地清理无效的连接
  • tcp_fin_timeout:参数表示当服务器主动关闭连接时,socket 保持在 FIN-WAIT-2 状态的最大时间
  • tcp_max_tw_buckets:参数表示操作系统允许 TIME_WAIT 套接字数量的最大值,如果超过这个数字,TIME_WAIT 套接字将立刻被清除并打印警告信息。该参数默认为 180000,过多的 TIME_WAIT 套接字会使 Web 服务器变慢
  • tcp_max_syn_backlog:参数表示 TCP 三次握手建立阶段接收 SYN 请求队列的最大长度,默认为 1024,将其设置得大一些可以使出现 Nginx 繁忙来不及 accept 新连接的情况时,Linux 不至于丢失客户端发起的连接请求
  • ip_local_port_range:参数定义在 UDP 和 TCP 连接中本地(不包括连接的远端)端口的取值范围
  • net.ipv4.tcp_rmem:参数定义 TCP 接收缓存(用于 TCP 接收滑动窗口)的最小值、默认值、最大值
  • net.ipv4.tcp_wmem:参数定义 TCP 发送缓存(用于 TCP 发送滑动窗口)的最小值、默认值、最大值
  • netdev_max_backlog:当网卡接收数据包的速度大于内核处理的速度时,会有一个队列保存这些数据包。这个参数表示该队列的最大值
  • rmem_default:参数表示内核套接字接收缓存区默认的大小
  • wmem_default:这个参数表示内核套接字发送缓存区默认大小
  • rmem_max:这个参数表示内核套接字接收缓存区的最大大小
  • wmem_max:这个参数表示内核套接字发送缓存区的最大大小

整理为表格:

参数作用您的设置
fs.file-max系统最大打开文件数999999
net.ipv4.tcp_tw_reuse启用 TIME-WAIT 重用1
net.ipv4.tcp_keepalive_timeTCP 保活时间(秒)600
net.ipv4.tcp_fin_timeoutFIN-WAIT-2 超时(秒)30
net.ipv4.tcp_max_tw_bucketsTIME-WAIT 最大数量5000
net.ipv4.ip_local_port_range本地端口范围1024-61000
net.ipv4.tcp_rmemTCP 接收缓冲区(最小/默认/最大)4096/32768/262142
net.ipv4.tcp_wmemTCP 发送缓冲区(最小/默认/最大)4096/32768/262142
net.core.netdev_max_backlog网络设备接收队列长度8096
net.core.rmem_default默认接收缓冲区大小262144
net.core.wmem_default默认发送缓冲区大小262144
net.core.rmem_max最大接收缓冲区大小2097152
net.core.wmem_max最大发送缓冲区大小2097152
net.ipv4.tcp_syncookies启用 SYN Cookies 防护1
net.ipv4.tcp_max_syn_backlogSYN 队列最大长度1024

执行编译

可以在 Nginx 官方网站(http://nginx.org/en/download.html)获取 Nginx 源码包。将下载的 nginx-1.28.0.tar.gz 源码压缩包放置到准备好的 Nginx 源代码目录中,然后解压

  • configure 命令检测操作系统内核和已经安装的软件,参数的解析,中间目录的生成以及根据各种参数生成一些 C 源码文件、Makefile 文件等
  • make 命令根据 configure 命令生成的 Makefile 文件编译 Nginx 工程,并生成目标文件、最终的二进制文件
  • make install 命令根据 configure 执行时的参数将 Nginx 部署到指定的安装目录,包括相关目录的建立和二进制文件、配置文件的复制
bash
tar -zxvf nginx-1.28.0.tar.gz
cd nginx-1.28.0
./configure
make
make install

补充:configure

./configure 是 Nginx 源码安装的第一步,也是最关键的步骤之一。它用于检测系统环境、配置编译选项和生成 Makefile

系统环境检测:

  • 检查编译器(gcc/clang)是否存在
  • 检测操作系统类型和架构
  • 检查必要的依赖库(如 PCRE、OpenSSL、zlib)
  • 验证目录权限和路径

生成 Makefile:根据检测结果和配置选项,生成适合当前系统的编译配置文件

配置安装路径和模块

允许自定义安装位置、启用或禁用特定功能

安装路径选项

控制 Nginx 的安装位置:

选项默认值说明
--prefix=PATH/usr/local/nginx安装根目录
--sbin-path=PATH$prefix/sbin/nginx可执行文件路径
--conf-path=PATH$prefix/conf/nginx.conf主配置文件路径
--error-log-path=PATH$prefix/logs/error.log错误日志路径
--pid-path=PATH$prefix/logs/nginx.pidPID 文件路径
--lock-path=PATH$prefix/logs/nginx.lock锁文件路径
--http-log-path=PATH$prefix/logs/access.logHTTP 访问日志路径
--modules-path=PATH$prefix/modules动态模块路径

示例

bash
./configure --prefix=/opt/nginx \
           --sbin-path=/usr/bin/nginx \
           --conf-path=/etc/nginx/nginx.conf

核心模块选项

控制包含哪些功能模块:

HTTP 相关模块

bash
# 内置模块(默认启用,可使用 --without 禁用)
--without-http_autoindex_module    # 禁用自动索引
--without-http_charset_module       # 禁用字符集
--without-http_gzip_module         # 禁用 Gzip
--without-http_ssi_module          # 禁用 SSI
--without-http_userid_module       # 禁用用户标识
--without-http_access_module       # 禁用访问控制
--without-http_auth_basic_module   # 禁用基本认证
--without-http_mirror_module       # 禁用镜像
--without-http_autoindex_module    # 禁用自动索引
--without-http_geo_module          # 禁用地理模块
--without-http_map_module          # 禁用 Map
--without-http_split_clients_module # 禁用 A/B 测试
--without-http_referer_module      # 禁用 Referer
--without-http_rewrite_module      # 禁用 URL 重写
--without-http_proxy_module        # 禁用代理
--without-http_fastcgi_module      # 禁用 FastCGI
--without-http_uwsgi_module        # 禁用 uWSGI
--without-http_scgi_module         # 禁用 SCGI
--without-http_memcached_module    # 禁用 Memcached
--without-http_limit_conn_module   # 禁用连接限制
--without-http_limit_req_module    # 禁用请求限制
--without-http_empty_gif_module    # 禁用空GIF
--without-http_browser_module      # 禁用浏览器识别
--without-http_upstream_hash_module # 禁用哈希负载均衡
--without-http_upstream_ip_hash_module # 禁用 IP 哈希
--without-http_upstream_least_conn_module # 禁用最少连接
--without-http_upstream_keepalive_module # 禁用长连接
--without-http_upstream_zone_module # 禁用共享内存

默认禁用的模块(需要使用 --with启用)

bash
# HTTP 模块
--with-http_ssl_module               # HTTPS 支持
--with-http_v2_module                # HTTP/2 支持
--with-http_v3_module                # HTTP/3 支持(需要 quiche)
--with-http_realip_module            # 真实 IP 提取
--with-http_addition_module          # 响应追加
--with-http_xslt_module              # XSLT 转换
--with-http_image_filter_module      # 图片处理
--with-http_geoip_module             # GeoIP
--with-http_sub_module               # 响应替换
--with-http_dav_module               # WebDAV
--with-http_flv_module               # FLV 流媒体
--with-http_mp4_module               # MP4 流媒体
--with-http_gunzip_module            # Gunzip
--with-http_gzip_static_module       # 预压缩文件
--with-http_auth_request_module      # 认证请求
--with-http_random_index_module      # 随机索引
--with-http_secure_link_module       # 安全链接
--with-http_degradation_module       # 降级
--with-http_slice_module             # 分片
--with-http_stub_status_module       # 状态页面
--with-http_perl_module              # Perl 嵌入
--with-http_xslt_module=dynamic      # 动态加载
 
# 邮件模块
--with-mail                          # 启用邮件代理
--with-mail_ssl_module               # 邮件 SSL
 
# Stream 模块
--with-stream                        # 启用 TCP/UDP 代理
--with-stream_ssl_module             # Stream SSL
--with-stream_realip_module          # Stream 真实 IP
--with-stream_geoip_module           # Stream GeoIP
--with-stream_ssl_preread_module     # Stream SSL 预读

依赖库路径

指定第三方库的位置:

bash
# 如果依赖库不在标准路径
--with-pcre=/path/to/pcre              # PCRE 库路径
--with-pcre-jit                       # 启用 PCRE JIT
--with-zlib=/path/to/zlib             # zlib 路径
--with-openssl=/path/to/openssl       # OpenSSL 路径
--with-openssl-opt=OPTIONS            # OpenSSL 编译选项
--with-libatomic                      # 原子操作库

编译器优化选项

bash
# 调试选项
--with-debug                          # 启用调试日志
--with-cc-opt=OPTIONS                 # 传递给编译器的选项
--with-ld-opt=OPTIONS                 # 传递给链接器的选项
 
# 示例:优化编译
--with-cc-opt="-O2 -march=native -pipe"
--with-ld-opt="-Wl,-rpath,/usr/local/lib"

其他重要选项

bash
# 用户和组
--user=nginx                          # 工作进程用户
--group=nginx                         # 工作进程组
 
# 线程池
--with-threads                        # 启用线程池
--with-file-aio                       # 启用异步 I/O
 
# 动态模块
--add-module=/path/to/module          # 添加第三方模块
--with-compat                         # 启用动态模块兼容性
--modules-path=/path/to/modules       # 动态模块路径

常用配置组合示例

  1. 最小化安装(仅基本 HTTP)
bash
./configure --prefix=/usr/local/nginx \
           --without-http_autoindex_module \
           --without-http_charset_module \
           --without-http_gzip_module \
           --without-http_ssi_module
  1. 生产环境推荐配置
bash
./configure --prefix=/usr/local/nginx \
           --user=nginx \
           --group=nginx \
           --with-http_ssl_module \
           --with-http_v2_module \
           --with-http_realip_module \
           --with-http_gzip_static_module \
           --with-http_stub_status_module \
           --with-http_sub_module \
           --with-pcre \
           --with-pcre-jit \
           --with-file-aio \
           --with-threads \
           --with-ld-opt="-Wl,-z,relro,--as-needed" \
           --with-cc-opt="-O2 -march=native -pipe -fPIC"
  1. 流媒体服务器
bash
./configure --prefix=/opt/nginx-media \
           --with-http_ssl_module \
           --with-http_v2_module \
           --with-http_flv_module \
           --with-http_mp4_module \
           --with-http_slice_module \
           --with-threads \
           --with-file-aio
  1. 反向代理负载均衡
bash
./configure --prefix=/usr/local/nginx-proxy \
           --with-http_ssl_module \
           --with-http_realip_module \
           --with-http_stub_status_module \
           --with-stream \
           --with-stream_ssl_module \
           --with-stream_realip_module \
           --with-stream_ssl_preread_module \
           --with-pcre \
           --with-pcre-jit
  1. 支持第三方模块
bash
# 添加 Nginx 官方模块
./configure --add-dynamic-module=../nginx-1.0.15/modules/ngx_http_geoip_module
 
# 添加第三方模块(如 ngx_cache_purge)
git clone https://github.com/nginx-modules/ngx_cache_purge.git
./configure --add-module=../ngx_cache_purge \
           --with-http_ssl_module

常见问题解决

  1. 缺少依赖错误
bash
# 在 Ubuntu/Debian
sudo apt-get install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
 
# 在 RHEL/CentOS
sudo yum install gcc make pcre-devel zlib-devel openssl-devel
  1. 查看完整选项列表
bash
./configure --help
  1. 保存配置信息
bash
# 在 configure 前创建一个配置文件
cat > build_config.sh << 'EOF'
#!/bin/bash
./configure \
  --prefix=/usr/local/nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --with-pcre \
  --with-pcre-jit \
  --with-file-aio \
  --with-threads
EOF
 
chmod +x build_config.sh
./build_config.sh
  1. 查看最终配置
bash
# 编译安装后查看实际配置
/usr/local/nginx/sbin/nginx -V
 
# 输出示例:
nginx version: nginx/1.0.15
built by gcc 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
built with OpenSSL 1.1.1f  31 Mar 2020
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module ...

最佳实践建议

  1. 从需求出发:不要启用不需要的模块,减少攻击面
  2. 明确路径:使用 --prefix指定安装目录,便于管理
  3. 包含常用模块:至少包含 http_ssl_modulehttp_v2_modulehttp_realip_module
  4. 启用性能特性pcre-jitfile-aiothreads
  5. 考虑动态模块:新版本 Nginx 推荐使用动态模块
  6. 记录配置:保存 configure 参数,方便后续维护
  7. 测试编译:先运行 make测试,成功后再 make install

Nginx 的命令行控制

在 Linux 中通常通过命令行来完成 Nginx 的启动、停止、重载配置、查看版本信息以及日志文件回滚等操作。默认情况下,Nginx 被安装在目录 /usr/local/nginx/ 中,其二进制文件路径为 /usr/local/nginx/sbin/nginx,配置文件路径为 /usr/local/nginx/conf/nginx.conf。在执行 ./configure 时,也可以通过 --prefix--sbin-path--conf-path 等参数将它们安装到不同目录。

Nginx 主命令及常用参数在最新稳定版中保持兼容,常见组合如下:

场景示例命令说明
启动(默认配置)/usr/local/nginx/sbin/nginx按默认路径启动
启动(指定配置文件)/usr/local/nginx/sbin/nginx -c /path/nginx.conf使用指定配置文件启动
启动(指定前缀目录)/usr/local/nginx/sbin/nginx -p /opt/nginx/以指定前缀目录运行
停止(快速)/usr/local/nginx/sbin/nginx -s stop立即终止所有进程
停止(优雅退出)/usr/local/nginx/sbin/nginx -s quit处理完当前请求后退出
重载配置/usr/local/nginx/sbin/nginx -s reload平滑加载新配置
重新打开日志文件/usr/local/nginx/sbin/nginx -s reopen配合日志切割重新打开日志文件
测试配置语法/usr/local/nginx/sbin/nginx -t检查语法和引用的文件
静默测试配置/usr/local/nginx/sbin/nginx -t -q仅在出错时输出信息
查看版本/usr/local/nginx/sbin/nginx -v仅显示版本号
查看版本和编译参数/usr/local/nginx/sbin/nginx -V显示版本与完整编译参数
查看帮助/usr/local/nginx/sbin/nginx -h显示命令行帮助

快速停止服务

使用 -s stop 可以强制停止 Nginx 服务。-s 参数告诉 Nginx 程序向正在运行的 Nginx 服务发送信号量,Nginx 程序通过 nginx.pid 文件中得到 master 进程的进程 ID,再向运行中的 master 进程发送 TERM 信号来快速地关闭 Nginx 服务。例如:

bash
/usr/local/nginx/sbin/nginx -s stop

实际上通过 kill 命令直接向 nginx master 进程发送 TERM 或者 INT 信号,效果是一样的。例如:通过 ps 命令来查看 nginx master 的进程 ID:

bash
ps -ef | grep nginx
# root     17784     1  0 19:56 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
# nobody   17785 17784  0 19:56 ?        00:00:00 nginx: worker process
# root     17968  1602  0 20:07 pts/0    00:00:00 grep --color=auto nginx
 
kill -s SIGTERM 17784

日志回滚扩展

手工切割访问日志:

bash
mv /usr/local/nginx/logs/access.log /usr/local/nginx/logs/access.log.$(date +%Y%m%d_%H%M%S)
/usr/local/nginx/sbin/nginx -s reopen

典型 logrotate 配置( /etc/logrotate.d/nginx ):

bash
/usr/local/nginx/logs/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 640 nobody nobody
    sharedscripts
    postrotate
        /usr/local/nginx/sbin/nginx -s reopen 2>/dev/null || true
    endscript
}

注意事项与常见问题

  • 建议先执行 nginx -t,确认配置正确后再 nginx -s reload
  • -s stop 会立即终止连接和进程,可能中断正在处理的请求,仅在紧急情况下使用。
  • 优先使用 -s quit 实现平滑下线,适用于生产环境维护。
  • 如果 -s reload 后配置未生效,应检查 error.log 中是否有 emergalert 等级错误。
  • 若系统中同时存在源码安装和包管理器安装的 Nginx,请通过 which nginxnginx -V 等命令确认实际使用的二进制路径和配置。

将 Nginx 注册为 systemd 服务的步骤:

将 Nginx 注册为 systemd 服务

检查 Nginx 安装信息

bash
# 确认 Nginx 可执行文件路径
ls -la /usr/local/nginx/sbin/nginx
 
# 确认 PID 文件存在
ls -la /usr/local/nginx/logs/nginx.pid
 
# 确认配置文件路径
/usr/local/nginx/sbin/nginx -t

创建 systemd 服务文件

/etc/systemd/system/nginx.service 创建服务文件:

ini
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
Restart=on-failure
RestartSec=10
 
[Install]
WantedBy=multi-user.target

配置说明

  • [Unit]:服务描述和依赖关系
  • [Service]
    • Type=forking:后台运行
    • PIDFile:PID 文件路径
    • ExecStartPre:启动前测试配置
    • ExecStart:启动命令
    • ExecReload:重载配置(HUP)
    • ExecStop:停止命令(QUIT)
    • Restart=on-failure:失败时自动重启
  • [Install]:设置开机自启

重新加载 systemd

bash
systemctl daemon-reload

常用管理命令

bash
# 启动服务
systemctl start nginx
 
# 停止服务
systemctl stop nginx
 
# 重启服务
systemctl restart nginx
 
# 重新加载配置(不中断服务)
systemctl reload nginx
 
# 查看服务状态
systemctl status nginx
 
# 启用开机自启
systemctl enable nginx
 
# 禁用开机自启
systemctl disable nginx
 
# 查看服务日志
journalctl -u nginx
 
# 测试服务功能
curl -I http://localhost

卸载 Nginx

当通过源码编译安装 Nginx 时,没有像包管理器那样的统一卸载命令。需要手动删除所有相关文件。以下是完整的卸载步骤:

停止 Nginx 服务

首先确保 Nginx 已停止运行:

bash
# 如果 Nginx 正在运行,停止它
sudo /usr/local/nginx/sbin/nginx -s stop
# 或者使用 pkill
sudo pkill -9 nginx

查找 Nginx 安装位置

在删除前,先确认安装位置(假设您使用的是默认路径):

bash
# 查看编译时的安装前缀(如果记得)
# 或者通过运行中的进程查找
ps aux | grep nginx
# 或者查找 nginx 可执行文件
whereis nginx
which nginx

删除 Nginx 相关文件

删除主程序文件(默认安装在 /usr/local/nginx

bash
# 删除整个 nginx 安装目录
sudo rm -rf /usr/local/nginx

如果指定不同的安装前缀:

plaintext
# 例如,如果编译时指定了 --prefix=/opt/nginx
sudo rm -rf /opt/nginx

删除可能的配置文件位置:

bash
# 常见的配置文件位置
sudo rm -rf /etc/nginx
sudo rm -rf /usr/local/etc/nginx

删除日志文件

bash
# 默认日志位置
sudo rm -rf /usr/local/nginx/logs
sudo rm -rf /var/log/nginx

删除临时文件

bash
sudo rm -rf /var/temp/nginx
sudo rm -rf /var/run/nginx*

删除系统服务文件

如果创建了 systemd 服务文件:

bash
# 停止并禁用服务
sudo systemctl stop nginx
sudo systemctl disable nginx
 
# 删除服务文件
sudo rm -f /lib/systemd/system/nginx.service
sudo rm -f /etc/init.d/nginx
sudo rm -f /etc/rc.d/init.d/nginx
 
# 重新加载 systemd
sudo systemctl daemon-reload

删除环境变量和手动链接

bash
# 检查 PATH 中是否有手动添加的链接
# 删除手动创建的符号链接
sudo rm -f /usr/bin/nginx
sudo rm -f /usr/sbin/nginx
sudo rm -f /usr/local/bin/nginx
 
# 检查并删除环境变量配置
sudo rm -f /etc/profile.d/nginx.sh

验证完全删除

bash
# 确认 nginx 不再运行
ps aux | grep nginx
 
# 确认 nginx 命令不可用
which nginx
nginx -v 2>&1
 
# 检查主要目录是否已删除
ls -la /usr/local/nginx 2>/dev/null || echo "目录已删除"

自动化卸载脚本

可以创建一个卸载脚本 uninstall_nginx.sh

bash
#!/bin/bash
echo "=== 开始卸载 Nginx ==="
 
# 停止 Nginx
echo "停止 Nginx 服务..."
sudo pkill -9 nginx 2>/dev/null
sudo systemctl stop nginx 2>/dev/null
sudo systemctl disable nginx 2>/dev/null
 
# 删除主程序
echo "删除 Nginx 文件..."
[ -d "/usr/local/nginx" ] && sudo rm -rf /usr/local/nginx
[ -d "/opt/nginx" ] && sudo rm -rf /opt/nginx
[ -d "/etc/nginx" ] && sudo rm -rf /etc/nginx
[ -d "/var/log/nginx" ] && sudo rm -rf /var/log/nginx
 
# 删除服务文件
echo "删除服务配置..."
[ -f "/lib/systemd/system/nginx.service" ] && sudo rm -f /lib/systemd/system/nginx.service
[ -f "/etc/init.d/nginx" ] && sudo rm -f /etc/init.d/nginx
[ -f "/etc/rc.d/init.d/nginx" ] && sudo rm -f /etc/rc.d/init.d/nginx
sudo systemctl daemon-reload 2>/dev/null
 
# 删除符号链接
echo "删除命令链接..."
[ -f "/usr/bin/nginx" ] && sudo rm -f /usr/bin/nginx
[ -f "/usr/sbin/nginx" ] && sudo rm -f /usr/sbin/nginx
[ -f "/usr/local/bin/nginx" ] && sudo rm -f /usr/local/bin/nginx
 
echo "=== Nginx 卸载完成 ==="

保存后执行:

plaintext
chmod +x uninstall_nginx.sh
sudo ./uninstall_nginx.sh

重要提醒

  1. 备份重要数据:在删除前,确保备份了以下内容(如果有):

    bash
    # 配置文件
    cp -r /usr/local/nginx/conf /tmp/nginx_conf_backup
    # 网站文件
    cp -r /usr/local/nginx/html /tmp/nginx_html_backup
    # 日志文件(如果需要分析)
    cp -r /usr/local/nginx/logs /tmp/nginx_logs_backup
  2. 记录编译参数:如果计划重新安装,最好先记录之前的编译参数:

    bash
    # 在删除前查看编译参数
    /usr/local/nginx/sbin/nginx -V

    这将输出类似以下信息,保存以备后用:

    plaintext
    nginx version: nginx/1.0.15
    built by gcc 8.3.0
    configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module
  3. 检查依赖:删除后可能需要清理一些编译时安装的开发包:

    bash
    # 例如,如果您安装了 PCRE、OpenSSL 等开发包
    # 但通常不建议删除,除非确定其他程序不需要