源码安装nginx
- 先安装下载工具:
yum install wget; - 创建文件夹并下载nginx源码:
cd /usr/local && mkdir software && cd software
wget https://nginx.p2hp.com/download/nginx-1.24.0.tar.gz
- 直接在当前目录解压:
tar -zxvf nginx-1.24.0.tar.gz
- 安装依赖软件包:
yum install -y gcc gcc-c++ make zlib-devel pcre-devel openssl-devel
- 配置编译参数:(由于
--prefix=path的path默认为/usr/local/nginx,故在此不做配置;--sbin-path、--modules-path、--conf-path、--error-log-path、--pid-path、--lock-path等6项是基于--prefix,故也不做配置。)- --with-http_ssl_module:https协议支持,构建和运行此模块需要 OpenSSL 库;
- --with-http_v2_module:支持HTTP/2;
- --with-http_realip_module:将客户端地址更改为指定标头字段中发送的地址;
- --with-http_gunzip_module:在 Nginx 服务器上解压缩传入的 Gzip 压缩过的请求体。当客户端通过 Gzip 压缩方式发送请求时,这个模块能够解压缩请求体,以便 Nginx 能够正常处理请求;
- --with-http_stub_status_module:提供了一个简单的状态页面,可以用于监控 Nginx 服务器的运行状态。通过这个状态页面,你可以获取一些关键的服务器信息,例如连接数、请求处理情况、内存使用等。
cd nginx-1.24.0
./configure --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gunzip_module --with-http_stub_status_module
- 编译并安装:
make && make install
- 在
/usr/local/nginx/conf/nginx.conf里将server.server_name改为你的IP,之后通过nohup /usr/local/nginx/sbin/nginx &开启nginx的后台运行。 - 阿里云服务器需要手动开放80端口。路径为:云服务器 ECS -> 网络与安全 -> 安全组 -> 实例的管理规则 -> 安全组详情里的入方向。
- 在浏览器里输入你的IP地址,回车。如果看到ngnix的欢迎页面,就表示成功了。
nginx相关命令:
./nginx -s reload # 重新加载nginx配置文件并重启nginx
./nginx # 启动nginx
./nginx -s stop # 强制停止nginx
./nginx -s reopen # 重启nginx
./nginx -s quit # 优雅的停止nginx
nginx -v # 查看nginx的版本
killall nginx # 杀死所有nginx进程
ps -ef | grep nginx # 查看nginx是否启动
跟随系统启动
- 进入到
/lib/systemd/system/目录并创建nginx.service:
cd /lib/systemd/system/ && vi nginx.service
写入内容:
[Unit]
Description=nginx service #服务的文本说明
After=network.target #表示该服务在网络服务启动后才启动
[Service]
Type=forking #定义服务的启动类型,以fork方式后台运行,即在启动时会派生一个子进程
ExecStart=/usr/local/nginx/sbin/nginx #服务启动时执行的命令
ExecReload=/usr/local/nginx/sbin/nginx -s reload #服务重载时执行的命令
ExecStop=/usr/local/nginx/sbin/nginx -s quit #服务停止时执行的命令
PrivateTmp=true #服务将在一个独立的临时文件系统中运行,可以提高安全性
[Install]
WantedBy=multi-user.target #定义在哪个target下启用该服务。multi-user.target表示在多用户模式下启用
- 加入开机自启动:
systemctl enable nginx
其他补充:
systemctl start nginx #启动nginx服务
systemctl stop nginx #停止服务
systemctl restart nginx #重新启动服务
systemctl status nginx #查看服务当前状态
systemctl disable nginx #停止开机自启动
systemctl list-units --type=service #查看所有已启动的服务