了解location
1、location 区段
- location 是在 server 块中配置,根据不同的 URI 使用不同的配置,来处理不同的请求。
- location 是有顺序的,会被第一个匹配的 location 处理。
- 先后顺序以及基本语法如下:
location [=|~|~*|^~|@] pattern{……}
2、location 前缀含义
= 表示精确匹配,优先级也是最高的
^~ 表示 url 以某个常规字符串开头,理解为匹配url路径即可
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配
!~ 表示区分大小写不匹配的正则
!~* 表示不区分大小写不匹配的正则
/ 通用匹配,任何请求都会匹配到
@ 内部服务跳转
动静分离
网页分静态网页(操作简单的css,js等)以及动态网页(涉及数据库的变化),我们负载均衡的时候就需要给这些网页区分以下才能更高效解决问题,简单来说,就是使用正则表达式匹配过滤,然后交个不同的服务器。
下面我们就实现一个有负载均衡的动静分离的代理Nginx
1.虚拟好网卡信息
998 ifconfig enp0s25:1 192.168.152.101
999 ifconfig enp0s25:2 192.168.152.102
1000 ifconfig enp0s25:3 192.168.152.103
1001 ifconfig enp0s25:4 192.168.152.104
1002 ifconfig enp0s25:5 192.168.152.105
1003 ifconfig enp0s25:6 192.168.152.106
2.配置四个app
server {
listen 192.168.152.101:80;
server_name www.app1.com;
root /usr/share/nginx/mytest1;
access_log /var/log/www.mytest1.com.log main;
error_log /var/log/www.mytest1.com.error.log;
location / {
index index.html;
}
}
其他的修改以下ip就完事
3.配置app所展示的服务
cd /usr/share/nginx/
mkdir mytest1{1..4}
echo " static 192.168.152.101" > mytest1/index.html
echo " static 192.168.152.102" > mytest2/index.html
echo " move 192.168.152.103" > mytest3/index.php
echo " move 192.168.152.104" > mytest4/index.php
4.配置代理
vim proxy.conf
upstream htmlserver {
server 192.168.152.101;
server 192.168.152.102;
}
upstream phpserver {
server 192.168.152.103;
server 192.168.152.104;
}
server {
listen 192.168.152.105:80;
server_name www.proxy.com;
root /usr/share/nginx/proxy;
access_log /var/log/www.proxy.com.log main;
error_log /var/log/www.proxy.com.error.log;
location ~ .*\.(html|gif|jpg|png|bmp|swf|jpeg)$ {
index index.html;
proxy_pass http://htmlserver;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 256k;
}
}
server {
listen 192.168.152.106:80;
server_name www.proxy.com;
root /usr/share/nginx/proxy;
access_log /var/log/www.proxy.com.log main;
error_log /var/log/www.proxy.com.error.log;
location ~ \.php$ {
index index.html;
proxy_pass http://phpserver;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 256k;
}
}
5启动服务,访问
curl 192.168.152.105/index.html
curl 192.168.152.105/index.html
curl 192.168.152.106/index.php
curl 192.168.152.106/index.php
正常显示内容即可
网友评论