环境
- VMWare虚拟机两台(已配置好LNPM, CentOs7)
实现目标
- 验证nginx的反向代理和负载均衡
步骤
-
配置访问的主域名
- cd /usr/local/nginx/conf/vhost
- touch main.com.conf
- vim main.com.conf
upstream myserver { server 127.0.0.1:8090; server 192.168.227.130:8090; } server { listen 80; server_name main.com; location / { proxy_pass http://myserver; } access_log /home/wwwlogs/main_access.log; error_log /home/wwwlogs/main_error.log; }
- 配置hosts
vim /etc/hosts
添加一行 127.0.0.1 main.com
-
配置实际服务器 a.com
- cd /usr/local/nginx/conf/vhost
- touch a.com.conf
- vim a.com.conf
server { listen 8090; server_name _; index index.html index.htm index.php; root /home/wwwroot/a; #error_page 404 /404.html; # Deny access to PHP files in specific directory #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; } include enable-php.conf; location /nginx_status { stub_status on; access_log off; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } include rewrite/thinkphp.conf; access_log /home/wwwlogs/a_access.log; error_log /home/wwwlogs/a_error.log; }
- cd /home/wwwroot/a/
- touch index.php
- vim index.php
<?php echo 'a.com'; ?>
-
配置另一台虚拟机的服务器, 地址 192.168.227.130, 域名 b.com 配置同a.com, 将index.php中输出改为 b.com
-
配置完成后,重启两台虚拟机的nginx服务 service nginx restart
-
这个时候,访问第一台虚拟机的main.com, nginx会将请求转发至 a.com 和 b.com, 每次刷新会看到输出的变化
-
还可以给两个服务器配置负载均衡的权重等