7. Nginx基础模块-虚拟站点+Location

1 Nginx虚拟站点

环境:在一台服务器上实现多个站点

1.1 实现虚拟主机的方式

  • 基于IP:不同的IP
  • 基于端口:相同IP,不同的端口
  • 基于域名:相同的IP,相同的端口,不同的域名
基于域名:相同的IP,相同的端口,不同的域名
charset utf-8;
server {
        listen 80;
        server_name baidu.yan.com;					//baidu是主机域
        location / {
                root /html/baidu;
                index index.html;
                access_log /var/log/nginx/baidu.access.log main;
        }
        location /baidu_status {
                stub_status;
        }
}
server {
        listen 80;
        server_name jingdong.yan.com;			//京东是主机域
        location / {
                root /html/jingdong;
                index index.html;
                access_log /var/log/nginx/jingdong.access.log main;
        }
}

在这里插入图片描述
在这里插入图片描述

2 Nginx Location

使用Nginx Location可以控制访问网站路径

2.1 Location语法优先级排列

匹配符 匹配规则 优先级
= 精确匹配 1
^~ 以某个字符串开头 2
~ 区分大小写的正则匹配 ** 3
~* 不区分大小写的正则匹配 ** 4
~! 区分大小写不匹配的正则 5
!~* 不区分大小写不匹配的正则 6
/ 通用匹配,任何请求都会匹配到 ** 7

2.2 配置网站验证location优先级

server {
        listen 88;
        server_name localhost;
        location / {
                default_type /test/html;
                index index.html;
                return 200  "location /";
                }
    	location = / {
           default_type /test/html;
            index index.html;
            return 200 "location = /";
            }
    	location ~ / {
            default_type /test/html;
            return 200 "location ~ /";
            }
    }

2.3 Location 应用场景

#通用匹配,任何请求都会匹配到
location 	/	{
	}

#严格区分大小写,匹配以.php结尾的都走这个location
location	~	\ .php$  {
		fastcgi_pass http://127.0.0.1:9000
	}

#严格区分大小写,匹配.jsp结尾的都走location
location ~ \ .jsp$ {
	porxy_pass http://127.0.0.1:8080;
}

#不区分大小写匹配,只要用户访问.jpg.gif.png,js,css都走这条location
location	~* 	.*\ .(jgp|gif|png|js|css)$	{
		rewrite	(.*) http://cdn.odlboyedu.com$request_uri;
}s

#不区分大小写匹配
location ~* "\ .(sql|bak|tgz|tar.gz)$" {
	default_type text/html;
	return 403 "启用访问控制成功"
}

猜你喜欢

转载自blog.csdn.net/weixin_43357497/article/details/113764096