1,安装准备
由于nginx的一些模块依赖一些lib库,所有这里要安装这些lib库
yum install gcc-c++
yum install pcre pcre-devel
yum install zlib zlib-devel
yum install openssl openssl-devel
2,安装 nginx
# 1.安装前查看是否安装过 nginx ,是的话先卸载
find -name nginx
yum remove nginx
# 2.进入 /usr/local
cd /usr/local
# 3.下载官网最新的nginx,然后解压
wget http://nginx.org/download/nginx-1.7.4.tar.gz
tar -zxvf nginx-1.7.4.tar.gz
# 4.这时会产生一个 nginx-1.7.4目录,进入该目录
cd nginx-1.7.4
# 5.安装(默认安装在/usr/local/nginx),可使用--prefix指定安装路径
./configure
make
make install
# 6.启动nginx,进入nginx的安装目录下的sbin目录(/usr/local/nginx/sbin)
./nginx
# 7.设置软连接
ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
# 8.nginx 常用命令
启动:nginx
重启:nginx -s reload
停止:nginx -s stop
# 9.启动后访问80端口,看是否显示nginx欢迎页面
# 如果是云服务器的话,还需要注意防火墙配置,及安全组。
3,nginx 配置
# 1,修改 nginx/conf 下的 nginx.conf 文件,最后的大括号内加入代码
include vhosts/*.conf;
# 2,在 conf 文件下新建 vhosts 文件夹
mkdir vhosts
# 3,进入 vhosts 目录,新建 test.conf,并键入以下代码
(我这里的需求是当访问127.0.0.1:3000/api时,转发到127.0.0.1:5757/api)
(可以根据你的需求自行更改)
server {
# nginx 服务器监听3000端口
listen 3000;
# 监听的服务名称
server_name 127.0.0.1;
# 代理有可能导致请求头丢失,以下三行保证请求一定会有请求头
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 转发
location /api {
proxy_pass http://127.0.0.1:5757/api;
add_header Access-Control-Allow-Origin *;
}
}
# 然后重启nginx,即可
nginx -s reload
4,设置 nginx 开机自启
# 1,在 /lib/systemd/system 下新建 nginx.service 文件
vim nginx.service
# 2,添加如下代码,然后保存退出
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
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
# 3,设置开机自启
systemctl enable nginx.service
# 4,其他命令
启动:systemctl start nginx.service
停止开机自启:systemctl disable nginx.service
查看服务当前状态:systemctl status nginx.service
重新启动服务:systemctl restart nginx.service
查看已启动的服务:systemctl list-units --type=service
4,可能出现的报错
nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
,解决办法:
/usr/local/nginx/sbin/nginx -c /home/programFiles/nginx-1.7.4/conf/nginx.conf
注:后边路径为nginx.conf文件位置
然后重启nginx:nginx -s reload