大网数据广告活动
服务器运维问答

regex rewrite in nginx to match year in the URL

· 52CE 我爱测

I am trying to write an nginx rewrite directive that redirects a URL like https://website.com/2018/11/20/dummytext/feed/ to https://website.com/2018/11/20/dummytext/ (removing the /feed/ in the end). I cannot just do a match for …

问题原文

原帖链接 · MultiformeIngegno · CC BY-SA 4.0

I am trying to write an nginx rewrite directive that redirects a URL like https://website.com/2018/11/20/dummytext/feed/ to https://website.com/2018/11/20/dummytext/ (removing the /feed/ in the end).

I cannot just do a match for (.*)/feed/ because I do not want to redirect https://website.com/feed/.

I've created this regex that matches all posts with /feed/ in the end, which appears to work: https://www.regextester.com/?fam=111507

This is what I have in nginx:

rewrite "^\b(19|[2-9][0-9])\d{2}\b\/(.*)\/feed\/?$" https://website.com/$1 permanent;

The first problem is that it does not appear to work (I have restarted nginx). When I visit a URL like https://website.com/2018/11/20/dummytext/feed/ I am not redirected anywhere. The second problem is that I'm not sure about this part https://website.com/$1 and whether it would actually cut the /feed/ from the URL keeping the rest of the URL as is.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

Not sure if Nginx supports \b, but you only need to use / (without a backslash).

You do not need to specify https://example.com in the replacement URI if the value remains unchanged. See this document for details.

In the example in your question, two values are captured ($1 and $2), but only one is used in the replacement URI.

Try:

rewrite "^/(19|[2-9][0-9])\d{2}/(.*)/feed/?$" /$1/$2/ permanent;

You mention that .* also matches zero characters, however, .+ matches at least one character. Also, the placement of multiple / characters in the pattern can avoid the /feed edge condition.

For example:

rewrite ^(/.+/)feed/?$ $1 permanent;

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-09-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。