Nginx配置之首页为静态文件

首页为 静态文件 的 情况

 

前提提交:

1、准备 D:\abc123 目录,放 2个文件,一个为 index.html

2、配置hosts

127.0.0.1 www.abc123.com

 

试验:

配置访问 目录下的首页index.html,尝试访问 目录下的  图片 1.png。

 

Part 1:在 location / 下配置(斜杠,通用匹配)

首页文件位于 D:\abc123 目录中,index.html,目录下还有其它文件。

Nginx配置如下:

location 下 使用 root:

server {
	listen       80;
	server_name  www.abc123.com;

	#charset koi8-r;

	sendfile        on;

	access_log  logs/abc123.access.log main;

	location / {
		root d:/abc123;
		index index.html;
	}

}

注意,上面的配置可 不用 index 参数。

 

locatioin 下 使用 alias:alias 参数 以 斜杠(/)结尾。

	location / {
		alias d:/abc123/;
		index index.html;
	}

 

如果 alias 不是 以斜杠结尾,则访问首页失败,提示“403 Forbidden”。

 

上面两种配置,除了会访问 D:\abc123 目录下的首页外,还会访问首页下的图片。

 

Part 2: 在 location = / 下配置(等号,精确匹配)

首页 在 location = / 下配置,但其它的URL 在 location / 或 其它规则下匹配。

 

失败的配置:提示“502 Bad Gateway

server {
	listen       80;
	server_name  www.abc123.com;

	#charset koi8-r;

	sendfile        on;

	access_log  logs/abc123.access.log main;

	location = / {
		root d:/abc123;
		index index.html;
	}

	location / {
		proxy_pass http://localhost:10001;
	}

}

 

进一步更改,成功的配置如下(增加下面的配置):

	location = /index.html {
		root d:/abc123;
	}

 

上面的配置后,访问 http://www.abc123.com/index.html、 http://www.abc123.com、 http://www.abc123.com/ 三个URL的页面相同,只不过后两者在 浏览器地址栏不会显示 末尾的 “/index.html”。

 

说明,location = / 下的 “index index.html;” 可以删除。

注意,将Part 2中的 root 改为 alias是不行的——访问失败。

 

Part 2展示了精确匹配,此时,除了首页的其它请求转发到 http://localhost:10001 处理(location / 配置)。

当然,这个通用匹配也可以是 静态文件的。

这个配置会 覆盖 http://localhost:10001 中配置的首页(/)。

 

注意,

按照Part 2配置后,不能访问 d:/abc123 目录下的 其它文件。

 

参考资料:

1、nginx location配置详细解释

https://www.cnblogs.com/jpfss/p/10232980.html

2、nginx的location root 指令

https://www.cnblogs.com/shihaiming/p/6183923.html

 

posted @ 2021-05-26 13:08  快乐的欧阳天美1114  阅读(1014)  评论(0)    收藏  举报