跳至主要內容

Linux安装Nginx

IT王小二约 691 字

Linux安装Nginx

作者:IT王小二

博客:https://itwxe.comopen in new window

记录一下Linux下安装Nginx过程。

一、准备工作

环境说明

  • Linux版本:Ubuntu22.04 / CentOS7(CentOS7即将停止维护,不再推荐)
  • Nginx版本:nginx-1.24.0

下载安装文件

采用源码包方式安装,进入目录(个人习惯/itwxe/software),下载安装文件,如果云服务器下载速度过慢也可本地下载后上传。

cd /itwxe/software
wget http://nginx.org/download/nginx-1.24.0.tar.gz

安装Nginx所需要的依赖

如果你是Ubuntu系统

# 更新依赖
apt update
# 安装nginx依赖
apt install build-essential libtool libpcre3 libpcre3-dev zlib1g-dev libssl-dev -y

如果你是CentOS系统

# 安装gcc、gcc-c++
yum -y install gcc
yum -y install gcc-c++

# 安装pcre 、zilb
yum -y install pcre*
yum -y install zlib*

# 安装openssl(若需要支持 https 协议)
yum -y install openssl
yum -y install openssl-devel

二、安装及配置Nginx

安装Nginx

解压安装包。

tar -zxvf nginx-1.24.0.tar.gz

为编译安装做准备,进入解压目录。

cd nginx-1.24.0

为编译安装做准备。

./configure --prefix=/itwxe/software/nginx \
--with-http_gzip_static_module \
--with-http_flv_module \
--with-http_ssl_module \
--with-http_sub_module \
--with-http_mp4_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_preread_module \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-http_v2_module \
--with-http_realip_module

注:

--prefix:设置安装路径。

--with-http_stub_status_module:支持nginx状态查询。

--with-http_ssl_module:支持https。

--with-pcre:为了支持rewrite重写功能,必须制定pcre。

--with-http_gzip_static_module:gzip模块

--with-stream: stream模块

编译安装。

make && make install

指定配置文件启动Nginx。

/itwxe/software/nginx/sbin/nginx -c /itwxe/software/nginx/conf/nginx.conf

在浏览器访问 ip,看到如下信息则安装成功。

Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

一些命令

修改自己的配置之后,验证配置是否正确,重启Nginx命令

# 进入目录
cd /itwxe/software/nginx/sbin

# 验证配置是否正确
./nginx -t
# 如果看到如下内容, 那么配置正确, 可以重启Nginx
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

# 重启Nginx, 之后就可以通过域名访问了, 哈哈
./nginx -s reload

Nginx开机自启

# 新建文件
vim /etc/systemd/system/nginx.service

# 添加内容
[Unit]
Description=nginx.server
After=network.target

[Service]
Type=forking
PIDFILE=/var/run/nginx.pid
ExecStart=/itwxe/software/nginx/sbin/nginx -c /itwxe/software/nginx/conf/nginx.conf
ExecRepload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后使用 systemctl enable nginx.service 开启 nginx 开机自启,重启 CentOS 查看效果。

# 启动nginx服务
systemctl start nginx.service

# 停止nginx服务
systemctl stop nginx.service

# 重启nginx服务
systemctl restart nginx.service

# 查看nginx服务当前状态
systemctl status nginx.service

# 设置nginx服务开机自启动
systemctl enable nginx.service

# 停止nginx服务开机自启动
systemctl disable nginx.service

结语:当然Nginx除了反向代理,还有负载均衡等功能,这个就不在本文章范围内了。