45
Centos7下nginx搭建反向代理配置

1.安装基础环境依赖

yum install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel telnet bind-utils -y

yum install psmisc wget telnet -y

yum install epel-release net-tools -y

2.下载nginx及编译安装

wget http://nginx.org/download/nginx-1.9.9.tar.gz

tar zxvf nginx-1.9.9.tar.gz

cd nginx-1.9.9

./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_addition_module --with-http_flv_module --with-http_gzip_static_module --with-http_realip_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_dav_module

make

make install

groupadd -r nginx

useradd -s /sbin/nologin -g nginx -r nginx

/usr/local/nginx/sbin/nginx -v

3.配置nginx及反向代理,编辑配置文件nginx.conf

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

user nginx nginx; #这里是nginx运行的用户

worker_processes 2; #设置nginx服务的worker子进程,比如设为2:

error_log logs/error.log; #去掉前面的#,记录nginx错误日志,方便检查bug:

pid logs/nginx.pid; #nginx的pid位置

events {

worker_connections 1024; #每个进程允许的最多连接数,

}

http {

include mime.types;

default_type application/octet-stream;

#把下面的#去掉,这是日志配置:

log_format main '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';

access_log logs/access.log main; #日志存放位置

#upstream就是配置负载均衡的,当然得两台以上才叫负载,我这里的ip69和68都是

#用的apache, 也许你们的是tomcat, 没关系,按这样配置一样可以,

upstream proxy_test {

server 192.168.4.69:80 weight=1; #如果你要测试,把这里换成你自己要代理后端的ip

server 192.168.4.68:80 weight=1;

#ip_hash; #当负载两台以上用ip来hash解决session的问题,一台就别hash了。

}

这是server段的配置

server {

listen 80;

server_name www.test.com; #要访问的域名,我这里用的测试域名,如果有多个,用逗号分开

charset utf8;

location / {

proxy_pass http://proxy_test; #这里proxy_test是上面的负载的名称,映射到代理服务器,可以是ip加端口, 或url

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

}

}

保存退出!

nginx平滑重启:nginx -s reload #加载刚刚加入的配置。

4、测试:

后端服务器开启,在192.168.4.69和68的网页文件位置添加测试文件test.html, 内容69上: this is test 69, 68上:this is test 68,这样方便查看访问到哪台了。

在本地配置好host,在\Windows\System32\drivers\etc\hosts 用记事本打开,在最后一行加入:192.168.4.72 www.test.com

然后使用cmd,ping www.test.com 是否能ping通这个192.168.4.72地址,如果ok,则继续

打开浏览器用www.test.com去访问后端服务器的文件,

如: www.test.com/test.html,

浏览器打开显示有this...说明配置ok了。

然后F5刷新一下,如果是68和69不停的切换,说明负载ok了。

 

这条帮助是否解决了您的问题? 已解决 未解决

提交成功!非常感谢您的反馈,我们会继续努力做到更好! 很抱歉未能解决您的疑问。我们已收到您的反馈意见,同时会及时作出反馈处理!