配置nginx反向代理,实现api.x.com域名代理本地9001端口
(1)安装nginx
[root@centos7 ~]# cd /data
[root@centos7 data]# ll nginx-1.16.1.tar.gz
-rw-r--r-- 1 root root 1032630 Mar 24 18:17 nginx-1.16.1.tar.gz
[root@centos7 data]# tar -zxvf nginx-1.16.1.tar.gz
[root@centos7 data]# yum install -y gcc pcre-devel openssl-devel zlib-devel
[root@centos7 data]# useradd -r -s /sbin/nologin nginx
[root@centos7 data]# cd nginx-1.16.1/
[root@centos7 nginx-1.16.1]# ./configure --prefix=/apps/nginx \
> --user=nginx \
> --group=nginx \
> --with-http_ssl_module \
> --with-http_v2_module \
> --with-http_realip_module \
> --with-http_stub_status_module \
> --with-http_gzip_static_module \
> --with-pcre \
> --with-stream \
> --with-stream_ssl_module \
> --with-stream_realip_module
[root@centos7 nginx-1.16.1]# make && make install
(2)创建网站目录文件
[root@centos7 ~]# cd /apps/nginx/html/
[root@centos7 html]# mkdir api.x.com
[root@centos7 html]# echo "api.x.com" > api.x.com/index.htm
(3)修改nginx的配置文件,添加虚拟主机 api.x.com,并设置反向代理相关信息
[root@centos7 ~]# vim /apps/nginx/conf/nginx.conf
#在http{}段中添加以下内容
server {
listen 80;
server_name api.x.com;
location / {
proxy_pass http://127.0.0.1:9001/;
}
}
server {
listen 9001;
server_name 127.0.0.1;
location / {
root html/api.x.com;
index index.html;
}
}
(4)设置 hosts 文件,使域名可以解析到主机,在 /etc/hosts 文件中添加域名解析
[root@centos7 ~]# vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.17.7 api.x.com #添加此行
(5 )重启nginx,进行测试
[root@centos7 ~]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@centos7 ~]# nginx -s reload
[root@centos7 ~]# curl http://api.x.com #可以看到反向代理成功了
api.x.com