案例1:通过Nginx搭建静态网站,基于IP过滤设置用户访问限制
实验环境
虚拟机server1作为Nginx服务器。
步骤
Step 1:修改配置文件
在server1中:
cd /usr/local/nginx
cd conf/
vim nginx.conf
Step 2:编辑Nginx配置文件
打开nginx.conf
文件,添加以下配置:
server {
listen 80;
server_name server1;
location / {
autoindex on;
allow 192.168.1.0/24; # 允许此IP段访问
deny all; # 默认拒绝所有访问
if ($remote_addr !~ "192.168.1.") {
return 403; # 如果IP不在允许的范围内,返回403
}
}
error_page 403 404 500 502 503 504 /50x.html;
}
listen 80;
:监听80端口。server_name server1;
:指定服务器名为server1
。location / {}
:配置根路径的访问规则。autoindex on;
:开启目录浏览。allow 192.168.1.0/24;
:允许192.168.1.0/24
网段的IP访问。deny all;
:拒绝所有其他IP访问。if ($remote_addr !~ "192.168.1.") { return 403; }
:如果请求的IP不匹配192.168.1.
,则返回403错误。
error_page 403 404 500 502 503 504 /50x.html;
:配置错误页面。
Step 3:重启Nginx服务
nginx -s reload
案例2:通过Nginx实现反向代理,访问后端web服务
实验环境
需要虚拟机server1和server2。server1作为Nginx服务器,server2安装Apache服务,server3作为客户端。
步骤
Step 1:修改配置文件
在server1中:
cd /usr/local/nginx
cd conf/
vim nginx.conf
Step 2:编辑Nginx配置文件
打开nginx.conf
文件,添加以下配置:
http {
include mime.types;
default_type application/octet-stream;
upstream backend {
server 192.168.1.2:80; # 定义后端Apache服务器地址
}
server {
listen 80;
server_name server1;
location / {
proxy_pass http://backend; # 反向代理到后端服务器
}
}
}
upstream backend {}
:定义一个名为backend
的后端服务器组。server 192.168.1.2:80;
:指定后端服务器的地址和端口。
proxy_pass http://backend;
:将请求转发到定义的backend
服务器组。
Step 3:在server2中安装并配置Apache
yum install httpd -y
echo "Hello from Apache!" > /var/www/html/index.html
systemctl start httpd
systemctl enable httpd
Step 4:在server3中测试
curl http://server1
预期输出:
Hello from Apache!
案例3:通过Nginx实现web服务的负载均衡
实验环境
server1作为Nginx服务器,server2和server3作为Apache服务器。
步骤
Step 1:修改配置文件
在server1中:
cd /usr/local/nginx
cd conf/
vim nginx.conf
Step 2:编辑Nginx配置文件
打开nginx.conf
文件,添加以下配置:
http {
include mime.types;
default_type application/octet-stream;
upstream backend {
server 192.168.1.2:80 weight=3; # server2权重为3
server 192.168.1.3:80 weight=1; # server3权重为1
}
server {
listen 80;
server_name server1;
location / {
proxy_pass http://backend; # 负载均衡到后端服务器组
}
}
}
upstream backend {}
:定义后端服务器组。server 192.168.1.2:80 weight=3;
:指定192.168.1.2
的权重为3。server 192.168.1.3:80 weight=1;
:指定192.168.1.3
的权重为1。
proxy_pass http://backend;
:将请求负载均衡到backend
服务器组。
Step 3:在server2和server3中安装并配置Apache
yum install httpd -y
echo "Hello from Apache on server2!" > /var/www/html/index.html
systemctl start httpd
systemctl enable httpd
# 在server3中:
yum install httpd -y
echo "Hello from Apache on server3!" > /var/www/html/index.html
systemctl start httpd
systemctl enable httpd
Step 4:在server3中测试
curl http://server1
预期输出会交替显示:
Hello from Apache on server2!
Hello from Apache on server3!
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。