一、下载 tar.gz 文件包
下载地址:http://nginx.org/en/download.html
点击会自动下载,下载成功后传到Centos服务器上。
二、安装相关依赖包
yum install gcc -c++
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
三、解压文件包
进入到文件包的目录下,执行命令
tar -zxvf nginx-1.18.0.tar.gz
四、编译安装
进入到解压后的文件夹中,执行命令
cd nginx-1.18.0/
./configure \
--prefix=/usr/local/nginx \
--conf-path=/usr/local/nginx/conf/nginx.conf \
--pid-path=/usr/local/nginx/conf/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi
命令执行后,会在 /usr/local 目录下生成一个名为 “nginx” 的文件夹
然后执行命令 make 编译
最后执行命令 make install 安装
五、启动Nginx
进入目录 /usr/local/nginx/sbin ,执行命令
cd /usr/local/nginx/sbin/
./nginx // 启动Nginx
./nginx -s stop // 停止Nginx(不管当前有没有处理任务,强制停止)
./nginx -s quit // 停止Nginx(处理完当前任务后,才会停止)
./nginx -s reload // 重启Nginx
六、测试运行
服务成功启动后,浏览器地址栏输入当前服务的 IP 地址,能看到 Nginx 的欢迎页表示安装完成。
七、修改配置文件
进入目录 /usr/local/nginx/conf 下,有个名为 “nginx.conf” 的配置文件,打开后发现默认端口是80。
我们将默认端口改为 “9090”,然后重启服务(必须重启服务,否则配置文件不会生效),刷新页面,发现页面进不去了。
此时我们在地址后加上端口,页面恢复正常。
八、使用nginx代理服务器做负载均衡
修改 /usr/local/nginx/conf 目录下的 “nginx.conf” 配置文件,在 http 模块下 server 模块内更改配置
#负载均衡配置start
location / {
proxy_pass http://127.0.0.1;
proxy_redirect default;
}
#负载均衡配置end
在 http 模块下 server 模块外添加配置
upstream 127.0.0.1{
server localhost:8080 weight=2;
server 192.168.101.128:9090 weight=1;
}
整个配置文件内容如下:
说明:当我们访问 http://localhost:8989/ 时,nginx会自动跳转到配置的两个服务器中的一个。weight:表示权重,数字越大,被分配到的可能性越大;若数字值一样大小,意味着请求将平均分配到每个服务器上。假设 192.168.101.128 服务器宕机了,那么nginx会自动转向另一台服务器。
注意:proxy_pass 后面设置的地址必须与 upstream 后面的地址一致!
补充:
1、启动nginx时报错:"upstream" directive is not allowed here in E:\nginx-1.18.0/conf/nginx.conf:50
原因:"upstream"配置信息位置写错,必须在 在 http 模块下,server 模块外。
解决方案:按照上图给的例子更改过来即可。
2、启动nginx时报错:bind() to 0.0.0.0:80 failed (10013: An attempt was made to access a socket in a way forbidden by its access permissions)
原因:端口被占用,nginx默认端口为80,会有其他的软件默认端口也是这,从而出现端口被占用的情况
解决方案:server 下 listen 监听端口更换一个即可。