Nginx教程(2)-虚拟主机Server与Location

什么是虚拟主机

虚拟主机,就是把一台物理服务器划分成多个“虚拟”的服务器,每一个虚拟主机都可以有独立的域名和独立的目录。

nginx 的虚拟主机就是通过 nginx.conf 中 server 节点指定的,想要设置多个虚拟主机,配置多个 server 节点即可

#user nobody;
worker_processes 1;
events {
	worker_connections 1024;
}
http {
	include mime.types;
	default_type application/octet-stream;
	sendfile on;
	keepalive_timeout 65;
	server {
		listen 80;
		server_name localhost;
		location / {
			root html;
			index index.html index.htm;
		}
		error_page 500 502 503 504 /50x.html;
		location = /50x.html {
			root html;
		}
	}
}

配置文件将会有一个专门的章节介绍,先说说server

listen表示虚拟主机的端口号,而server_name表示访问虚拟主机的方式,访问虚拟主机的方式为server_name:listen(即127.0.0.1:80)

server {
	listen 8080;
	server_name test.com;
	location / {
		root html;
		index index.html index.htm;
	}
	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root html;
	}
}

那么想要访问此虚拟主机为test.com:8080
虚拟主机可以根据域名和IP以及不同的端口号进行配置

location

定义虚拟主机资源的路径以及访问方式

location / {
#location 是访问的 url 的匹配设置
	root html;
	#url 当前匹配后访问的跟目录,root 可以是任意的目录,通常使用 nginx 来作为静态资源服务器
	index index.html index.htm;
	#默认索引页面
}

当访问为www.test.com,将访问root下(html),默认索引页(index.html)
当访问为www.test.com/2.html,将访问root下(html)的2.html

location可以有多个,可以对location进行配置,根据url来判断,访问指定的location

location配置

语法规则: location [=||*|^~] /uri/ { … }
= 开头表示精确匹配
www.test.com/3.html

location = /3.html {
	root html;
}

^~ 开头表示 uri 以某个常规字符串开头,理解为匹配 url 路径即可。
www.test.com/static/a.html

location ^~ /static/ {
	root html;
}

~ 开头表示区分大小写的正则匹配
www.test.com/a.htm

location ~ \.(htm) {
	root html;
}

.(htm)为正则表达式

~* 开头表示不区分大小写的正则匹配

/ 通用匹配,任何请求都会匹配到。

多个 location 配置的情况下匹配顺序为,首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值