nginx 反向代理Apache

2014年1月13日 18:15:25

同一个域名下,不同uri走不同的应用(不同的web根目录)

实现方式:

Apache分别监听两个端口,对应不同的应用

nginx监听80端口,利用location指令根据匹配目录的不同将请求转发到不同的端口

nginx和Apache都在同一台windows上

nginx下载windows版本,解压->简单配置下->保证能启动nginx

命令行启动时要注意:要进入到解压文件内去执行nginx.exe不能简单的写到环境变量了事

下边是我的主配置文件(这些配置足够启动nginx了):

nginx.conf

 1 #user  nobody;
 2 worker_processes  1;
 3 
 4 error_log  F:/vc9server/nginx/logs/error.log;
 5 error_log  F:/vc9server/nginx/logs/error.log  notice;
 6 error_log  F:/vc9server/nginx/logs/error.log  info;
 7 
 8 pid        F:/vc9server/nginx/logs/nginx.pid;
 9 
10 events {
11     worker_connections  1024;
12 }
13 
14 http {
15     include       mime.types;
16     default_type  application/octet-stream;
17 
18     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
19                      '$status $body_bytes_sent "$http_referer" '
20                      '"$http_user_agent" "$http_x_forwarded_for"';
21 
22     access_log  F:/vc9server/nginx/logs/access.log  main;
23 
24     sendfile        on; #跟内核交互用 缓存
25     #tcp_nopush     on;
26 
27     #keepalive_timeout  0;
28     keepalive_timeout  65;
29     
30     server_names_hash_bucket_size 64;
31     include        apache.conf; #主要的反向代理配置都写在这个文件里了
32 }

apache.conf

 1 ##2014年1月11日
 2 #反向代理
 3 upstream zend 
 4 {
 5     server 127.0.0.1:8089;
 6 }
 7 
 8 upstream yaf 
 9 {
10     server 127.0.0.1:8088;
11 }
12 
13 server 
14 {
15     listen       80;
16     server_name  www.example1.com;
17     
18     location ^~ /abc {
19         proxy_pass      http://zend; #转发到上边定义的zend代理中去
20 
21         proxy_redirect          off;
22         proxy_set_header        Host $host;
23         proxy_set_header        X-Real-IP $remote_addr;
24         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
25     }
26     
27     location / 
28     {
29         proxy_pass      http://yaf; #转发到上边定义的yaf代理中去
30 
31         proxy_redirect          off;
32         proxy_set_header        Host $host;
33         proxy_set_header        X-Real-IP $remote_addr;
34         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
35         proxy_set_header         X-Scheme $scheme;
36     }
37 }    
38 server 
39 {
40     listen       80;
41     server_name  www.example2.com;
42         
43     location / 
44     {
45         proxy_pass      http://zend; #转发到zend代理
46 
47         proxy_redirect          off;
48         proxy_set_header        Host $host;
49         proxy_set_header        X-Real-IP $remote_addr;
50         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
51     }
52 }

解释:

1.请求 example1 时

URI为/abc开头的转发到上边定义的zend代理,其余的URI请求转到yaf代理

2.请求 example2 时

将所有请求转发到zend代理

3.配置中的proxy_set_header 是将nginx得到的请求信息(头信息等等)复制一份给代理服务器

4.nginx指令要有分号结尾,监听多个域名时,域名间用空格隔开后再以分号结尾

最后

在Apache中监听apache.conf中zend,yaf两个代理指定的域名+端口 或 ip+端口,并作相应的配置

nginx 和 Apache重启后浏览器里访问试试