请教一个 Nginx 设置默认页面的问题

2017-05-28 08:56:50 +08:00
 lxy

为了去掉 URL 中的 .html 后缀,用了如下配置

	location /test_html {
		alias /path/to/html/;
		index default.html;  # 默认页面
		default_type "text/html";
		try_files $uri.html =404;
	}

/path/to/html/ 目录结构

.
├── default.html
├── example.html
└── testme
    └── default.html

然而当我访问 localhost/test_html/ 或 localhost/test_html/testme/ 时,无法返回设置的默认的 default.html 页面(除非在 URL 后加 default,如 localhost/test_html/default )。试过改成 index default; 也不行。

应该怎么配置才能做到返回默认页面呢?

(如果将 default.html 重命名为无文件名的 .html 文件,可以解决问题,但是太丑陋,也不知道以后前端构建时会不会出现莫名其妙的问题)

8823 次点击
所在节点    NGINX
10 条回复
just1
2017-05-28 09:03:40 +08:00
try_files $uri $uri.html =404;
试试
lxy
2017-05-28 09:12:06 +08:00
@just1 不行
访问 localhost/test_html/ 时, $uri 是空的,只会返回无文件名的 .html 文件
oott123
2017-05-28 09:59:10 +08:00
try_files $uri $uri/ $uri.html =404;
gulangyu
2017-05-28 10:16:23 +08:00
借楼请教下,不使用 rewrite 到自定义页面的方法,怎么修改 Nginx 自带文件,来修改默认的 403 页面
403 Forbidden
-----------------
nginx
gulangyu
2017-05-28 10:18:18 +08:00
补充: 想知道 403 Forbidden 这几个字在 Nginx 的哪个地方?
lxy
2017-05-28 10:23:23 +08:00
@oott123 也行。虽然不太懂为什么。
不过有个小隐患,如果有个与 testme 目录同名的 testme.html 同在 test_html 目录下,会导致怎么也访问不到 testme.html。
尝试变更 try_files 顺序可以解决,应该没什么小坑了:try_files $uri.html $uri $uri/ =404;
jasontse
2017-05-28 10:29:56 +08:00
@gulangyu src/http/ngx_http_special_response.c
voocel
2017-05-29 03:00:58 +08:00
@gulangyu 你 return
voocel
2017-05-29 03:02:38 +08:00
@gulangyu 你 return 403, http 协议就会给你返回的 403 Forbidden 吧
gulangyu
2017-05-29 07:55:39 +08:00
@voocel 哦,那说错了,不是 rewrite,我的本意是 error_page 403

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/364384

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX