最近领导要求搞nginx服务器,那就搞搞看。
反向代理,一听这个词我就头大。代理还好理解,就是别人帮你做事,但这里又出来个反向代理。
里面就引出问题来了,什么是代理?什么是反向代理?他们有什么区别?如何在nginx里面设置反向代理?
先看看转载的文章:http://www.linuxidc.com/Linux/2015-01/111702.htm
这里面介绍的比较详细。
1. 配置固定的反向代理
我们先看看:nginx-1.9.3\conf\nginx.conf这个文件,里面有如下一段:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
....................
只要修改为:
server {
listen 8013;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://www.oldmtn.com;
#root html;
#index index.html index.htm;
}
.................
就可以实现代理,这样做,只要我们在本地浏览器输入:127.0.0.1:8013,就自动显示www.oldmtn.com的内容,如下图:
2. 使用反向代理的关键字配置
同样的,只要做如下配置即可。其中8080端口是我安装的tomcat服务器的地址。这里实现的功能是,访问127.0.0.1:8013会显示127.0.0.1:8080的内容。
upstream loadbance {
server 127.0.0.1:8080;
}
server {
listen 8013;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://loadbance;
#root html;
#index index.html index.htm;
}结果如下图:
3. 使用自定义的http服务器配置
上面我们是使用tomcat来进行模拟的,其实我们还可以使用自己定义的http服务器来进行配置.
之前我写了一篇文章,《简易Web服务器 》,我们也可以配置nginx.conf使其对应的代理服务器为我们自己定义的代理服务器。
下面是完整的nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream loadbance {
server localhost:8001;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://loadbance;
# root html;
# index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
本文详细解释了代理与反向代理的概念,并通过示例展示了如何在Nginx中实现反向代理,包括配置固定代理、使用关键字配置及自定义HTTP服务器配置。
928

被折叠的 条评论
为什么被折叠?



