我需要针对以下问题的nginx重写规则:
我的网址包含多个连字符,最后是下划线
示例请求:http://www.example.com/cat/cat2/200-AB---a-12_12-123.312/cat-_-cat/cat/dog---I
会出现404错误 所以需要301-重定向到:
http://www.example.com/cat/cat2/200-AB-a-12-12-123.312/cat-cat/cat/dog-I
因此所有下划线都应该用连字符替换,一次只能有一个连字符。
简短版本: 替换---用 - 并用 - 替换_ 但是用_替换_这个-_-将变成---并且必须再次调用规则1。
是否有可能在一条规则中?如果不是如何做任何其他方式:)我完全不知道如何使用nginx
任何帮助表示赞赏:)
答案 0 :(得分:1)
% nginx -c $PWD/test.conf
% curl -I localhost:8080/cat/cat2/200-AB---a-12_12-123.312/cat-_-cat/cat/dog---I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.3.13
Date: Wed, 20 Feb 2013 00:09:50 GMT
Content-Type: text/html
Content-Length: 185
Location: http://localhost:8080/cat/cat2/200-AB-a-1212-123.312/cat-cat/cat/dog-I
Connection: keep-alive
% cat test.conf
events { }
#error_log logs/error.log debug;
http {
server {
listen 8080;
location /cat/cat2/ {
# replace up to 3 inconsecutive
# uderscores per internal redirect
rewrite "^(.+?)_+(?:(.+?)_+)?(?:(.+?)_+)?(.+)$" $1$2$3$4 last;
# replace up to 3 inconsecutive multiple
# hyphens per internal redirect
rewrite "^(.+?-)-+(?:(.+?-)-+)?(?:(.+?-)-+)?(.+)$" $1$2$3$4 last;
return 301 $uri;
}
}
}