Linux系统中nginx的安装和使用

作者:陆金龙    发表时间:2022-04-11 22:35   

关键词:nginx  

一、安装nginx

1. gcc 安装
安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境,如果没有 gcc 环境,则需要安装:

yum install gcc-c++

2. PCRE pcre-devel 安装
PCRE(Perl Compatible Regular Expressions) 是一个Perl库,包括 perl 兼容的正则表达式库。nginx 的 http 模块使用 pcre 来解析正则表达式,所以需要在 linux 上安装 pcre 库,pcre-devel 是使用 pcre 开发的一个二次开发库。nginx也需要此库。命令:

yum install -y pcre pcre-devel

3. zlib 安装
zlib 库提供了很多种压缩和解压缩的方式, nginx 使用 zlib 对 http 包的内容进行 gzip ,所以需要在 Centos 上安装 zlib 库。

yum install -y zlib zlib-devel

4. OpenSSL 安装
OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。
nginx 不仅支持 http 协议,还支持 https(即在ssl协议上传输http),所以需要在 Centos 安装 OpenSSL 库。

yum install -y openssl openssl-devel

5. 安装wget 

未安装会提示 wget: command not found

yum -y install wget

6.下载 安装ngix

1)直接下载.tar.gz安装包,地址:https://nginx.org/en/download.html

     或命令下载 wget -c https://nginx.org/download/nginx-1.17.0.tar.gz

2)解压 tar -zxvf nginx-1.17.0.tar.gz

3)cd nginx-1.17.0

其实在 nginx-1.17.0 版本中你就不需要去配置,使用默认配置就可以了。
使用默认配置,执行以下命令

./configure

或者 自定义配置(不推荐)

./configure --prefix=/usr/local/nginx

4)编译安装

make

make install  # 如果未执行第3步的./configure 命令,会提示 No targets specified and no makefile found.

查找安装路径:

whereis nginx

二、启动、停止nginx

cd /usr/local/nginx/sbin/

./nginx  #启动

./nginx -s stop

./nginx -s quit

./nginx -s reload

报错:Nginx: [error] open() "/usr/local/Nginx/logs/Nginx.pid" failed(2:No such file or directory)解决方法:/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

查询nginx进程:

ps aux|grep nginx

三、重启 nginx

1.先停止再启动(推荐):
对 nginx 进行重启相当于先停止再启动,即先执行停止命令再执行启动命令。如下:

cd /usr/local/nginx/sbin/

./nginx -s quit

./nginx

2.重新加载配置文件:
当 ngin x的配置文件 nginx.conf 修改后,要想让配置生效需要重启 nginx,使用-s reload不用先停止 nginx再启动 nginx 即可将配置信息在 nginx 中生效,如下:
./nginx -s reload

启动成功后,在浏览器可以看到这样的页面:

四、开机自启动

即在rc.local增加启动代码就可以了。

vi /etc/rc.local

增加一行 /usr/local/nginx/sbin/nginx,如果报错: 'readonly' option is set (add ! to override),使用root账号执行。

 

五、配置反向代理

以上安装方法nginx的配置文件位于

/usr/local/nginx/conf/nginx.conf

vi /usr/local/nginx/conf/nginx.conf

Nginx配置文件结构的依次是「http」「server」「location」等等

示例:将git.klfront.com 转到http://www.klfront.com:8082;

    server {

        listen       80;

        server_name  git.klfront.com;

        location / {

            proxy_pass http://127.0.0.1:8082;

            proxy_connect_timeout 300s;

            proxy_send_timeout 300s;

            proxy_read_timeout 300s;

       }

    }