nginx 路由大小写适配

2015-01-19 11:16:59 +08:00
 iyuyue
请教一个问题,如果想让某个目录的路由不对大小写敏感。比如example.com/coolexample.com/Cool 映射到 cool 目录,应该怎么配置呢?

我自己尝试失败了,
location ~* /cool/ {
index index.html;
php ....
}
3657 次点击
所在节点    问与答
18 条回复
ryd994
2015-01-19 13:13:07 +08:00
大小写混用是什么奇葩坏习惯?
~*只是说/cool/ 和/Cool/都会由这个location块处理,但实际处理时就会找不到文件
如果你只是需要一个quick and dirty的话,可以ln -s cool Cool
ylhawj
2015-01-19 14:02:23 +08:00
windows是不区分大小写的,所以需要程序中将url统一按照小写或者大写处理就好了。
iyuyue
2015-01-19 14:19:21 +08:00
@ryd994 额,想做到不区分大小写,这样用户可以按自己喜欢的方式来输入。类似于Github。可以用alias来实现么?我试了下会陷入循环= =
iyuyue
2015-01-19 14:21:36 +08:00
@ylhawj 在Mac和Linux用户能看到大小写的情况下,nginx可以把url统一处理成小写的么?
jasontse
2015-01-19 14:23:08 +08:00
@iyuyue
Github 不是系统路径,而是参数查询数据库吧。
iyuyue
2015-01-19 14:24:35 +08:00
@jasontse 嗯是的。。看来要用lua,虽然这个问题的确很奇葩 = =
ylhawj
2015-01-19 14:24:40 +08:00
@iyuyue 嗯,这样的处理方法很多种,比如说Google下,http://www.myhack58.com/Article/sort099/sort0102/2014/51879.htm,这样的。
iyuyue
2015-01-19 14:28:45 +08:00
@ylhawj 哦哦,多谢。我搜到过这篇...当时看到要重新编译就直接跳过了= =
ryd994
2015-01-20 09:40:55 +08:00
@iyuyue 如果你只有这一个或者几个路径的话可以rewrite解决。用location ~* 然后里面rewrite到小写,但是要注意加last 防止死循环
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
不过按照location的匹配顺序,路径是优先于regex,似乎不加也可以……你自己试试吧……
iyuyue
2015-01-20 12:33:15 +08:00
@ryd994 抱歉,我试了一下rewrite .* /cool/ last; 然后500了。 能再说的详细一点么?我对nginx的正则有点晕= =
ryd994
2015-01-21 23:38:04 +08:00
@iyuyue 500看error log啊
ryd994
2015-01-21 23:40:45 +08:00
你要有两个location啊,一个正则的用来改写,一个静态小写的用来实际提供服务
处理的时候小写的因为是静态规则所以会优先匹配
ryd994
2015-01-21 23:42:14 +08:00
或者你可以试试用break而不是last
iyuyue
2015-02-10 10:57:24 +08:00
@ryd994 抱歉。。后来忙别的忘了回复。最后实现的是这样的
location ~ /cool/ {
index index.html;
....
}

location ~* /cool/ {
rewrite .* /cool/ last;
}
ryd994
2015-02-10 13:07:54 +08:00
@iyuyue 这…………两次regex你不感到蛋疼么…………
location ^~ /cool/ {
index index.html;
....
}

location ~* /cool/ {
rewrite .* /cool/ last;
}
这样就最多只需要一次regex,如果进来就是小写的话就不会检查regex
iyuyue
2015-02-10 13:33:58 +08:00
@ryd994 哦哦 是哦~ 多谢!
iyuyue
2015-02-10 13:37:07 +08:00
@ryd994 另外加了这两个之后,nginx就不会再自动补全目录名称后面的 / 了。。。你有什么好办法么?
ryd994
2015-02-10 14:24:29 +08:00
@iyuyue

>If a location is defined by a prefix string that ends with the slash character, and requests >are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, or >memcached_pass, then the special processing is performed. In response to a request with >URI equal to this string, but without the trailing slash, a permanent redirect with the >code 301 will be returned to the requested URI with the slash appended.

照例说应该是这样,为什么没有我也不知道。

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

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

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

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

© 2021 V2EX