Nginx 搭建静态资源服务

时间:2022-07-26
本文章向大家介绍Nginx 搭建静态资源服务,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 静态网页服务

  首先将静态的 web 上传到服务器之后,在 /nginx/conf 目录中修改 nginx.conf 文件,参考如下,修改完毕后进入 /nginx/sbin 目录中执行 nginx -s reload 重启 Nginx。然后请求对应 ip/域名 + 端口 + 资源 地址就可以访问到网页。

server {
	// 监听的端口号
	listen       80;
	// server 名称
	server_name  localhost;

	// 匹配 api,将所有 :80/api 的请求指到指定文件夹
	location /api {
		// web 的根目录
		root   /mnt/web/youhtml;
		// 默认打开 index.html
		index  index.html index.htm;
	}
	
	// 全匹配,将所有 80 端口的请求指到指定文件夹
	location / {
		// web 的根目录
		root   /mnt/web/myhtml;
		// 默认打开 index.html
		index  index.html index.htm;
	}
}

☞ listen 写法 listen *:80 | *:8080:监听所有 80 端口和 8080 端口 listen IP_address:port:监听指定的 IP 地址和端口号 listen IP_address:监听指定 IP 地址所有端口 listen port:监听该端口的所有 IP 连接

1.2 图片/视频服务

  图片、视频服务与静态网页服务配置一样,将文件放到统一的文件夹,然后使用 Nginx 将请求指到对应文件夹即可。文档等也可以使用此方式,但是浏览器不能解析的文件会直接弹出下载,可以解析的会被解析。

server {
	// 监听的端口号
	listen       80;
	// server 名称
	server_name  localhost;

	// 匹配 80 端口所有 /img 请求
	location /img {
		// 图片文件的根目录
		root   /mnt/img;
	}
	
	// 匹配 80 端口的所有 /video 请求
	location /video {
		// 视频文件的根目录
		root   /mnt/video;
	}
}