求助 nginx 大神看看这个奇怪的问题

2017-10-27 02:06:07 +08:00
 xiangin

配置如下

location ~* ^/a(.*)/(.*)$ {

	set $c $1;

	set $d $2;

	alias /var/www/xx.xxx.xxx/a$c/$d;

	fancyindex on;

	fancyindex_exact_size off;

	fancyindex_localtime on;

	if ( $d ~* .*\.(txt|log|js|css)$) {

		more_clear_headers "content-type";       
    
		add_header Content-Type text/plain;     
    
	}
}

现在的问题是访问 xx.xxx.xxx/axx/ 下面任何带有中文或者空格的资源(非 txt,log,js,css 结尾的)的时候都会 404,日志我也看了,编码没有问题。只要把 if 语句去掉就 OK。是在找不到原因了。 大佬求助

2951 次点击
所在节点    NGINX
10 条回复
Sikoay
2017-10-27 02:09:46 +08:00
萌新的想法:正则写对了吗
ryd994
2017-10-27 03:58:37 +08:00
1. 不要用 if,把 if 换成
location ~* .*\.(txt|log|js|css)$
2. $c 和$d 没有任何意义,怕$1 有歧义的话用 named capture
3. error.log
ryd994
2017-10-27 03:59:47 +08:00
照你的意思,英文没问题是么?
那就九成九是编码,或者 LANG
你怎么安装和启动 nginx 的?
ryd994
2017-10-27 04:00:24 +08:00
最后 -d 是判断目录是否存在
RTFM
ryd994
2017-10-27 04:03:32 +08:00
root /var/www/xx.xxx.xxx/;
location /a {
fancyindex on;
fancyindex_exact_size off;
fancyindex_localtime on;

if ( $d ~* .*\.(txt|log|js|css)$) {

more_clear_headers "content-type";

add_header Content-Type text/plain;

}
}
ryd994
2017-10-27 04:05:39 +08:00
root /var/www/xx.xxx.xxx/;
location /a {
fancyindex on;
fancyindex_exact_size off;
fancyindex_localtime on;
location ~* .(txt|log|js|css)$ {
more_clear_headers "content-type";
add_header Content-Type text/plain;
}
}

更好的办法是修改 /etc/nginx/mime.types
isCyan
2017-10-27 09:39:41 +08:00
没仔细看,先提醒一句 nginx if 里面不能有 rewrite 和 return 之外的指令。
你可以搜索 nginx if is evil
ryd994
2017-10-27 12:34:49 +08:00
@isCyan 理论上这种还是可以的,毕竟是基于路径的 if。但是有没有坑,我也说不清楚。
rewrite 因为是同模块所以肯定没事
return 因为立刻终止,所以一般也没事。
其他的具体分析太复杂,除非对 rewrite 和里面的指令的相关模块非常熟悉,很难判断。
if 最主要的坑在于,对于其他模块的指令,会生成两份配置,然后切换。然而 nginx 的指令是 declarative 的,所以实际上不保证顺序(虽然有 phase 会分隔)。if 执行的时候,可能相关变量根本不可用,或者里面的指令已经执行过了。

不过正常人都是去改 /etc/nginx/mime.types
或者加一个 types
http://nginx.org/en/docs/http/ngx_http_core_module.html#types
ryd994
2017-10-27 12:37:24 +08:00
用好嵌套 location 和 map 可以消除绝大多数 if
if 是 map 出现前的,仿 apache 的,不 nginx 的产物
用 if,出什么问题都是活该
xiangin
2017-10-27 14:12:05 +08:00
在这里统一感谢各位,最后重写了 mime.types 搞定,因为规则比较多,还有其他业务,不能直接改 /etc/nginx/mime.types,另外搞了一份 types,然后在 location 里面使用 include /etc/nginx/XXX.types;

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

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

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

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

© 2021 V2EX