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

Finish processing rewrite directives in location and return 301

· 52CE 我爱测

I have the following in my nginx.conf: location ~* /collections.*?products/([^/]+)/?$ { rewrite ^/collections.*?products/([^/]+)/?$ /$1.html; rewrite ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3; rewrite ^([^_]*)_(.*)$ $1-$2 permanent; } To r…

问题原文

原帖链接 · Nick Rolando · CC BY-SA 3.0

I have the following in my nginx.conf:

location ~* /collections.*?products/([^/]+)/?$ {
    rewrite ^/collections.*?products/([^/]+)/?$ /$1.html;
    rewrite ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3;
    rewrite ^([^_]*)_(.*)$ $1-$2 permanent; 
}  

To rewrite requests such as

"/collections/products/someproduct/" to "/someproduct.html"
"/collections/products/some_product/" to "/some-product.html"
"/collections/products/some_other_product/" to "/some-other-product.html"

However I can only get a 301 redirect to occur if the last rewrite directive (containing the permanent flag) matches and processes, e.g. my 2nd example. In the other 2 instances I get a 302 temporary redirect. How can I process these multiple rewrite directives in this location block and return 301 redirect regardless which ones match? If I put a permanent flag on all rewrite directives, it will stop processing after first match.

已采纳解答

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

You can convert _ to - recursively and independently of the rewrite...permanent.

For example:

location ~* /collections.*?products/([^/]+)/?$ {
    rewrite ^(.*)_(.*)$ $1-$2 last;
    rewrite ^/collections.*?products/([^/]+)/?$ /$1.html permanent; 
}

The second rewrite is executed only after the first rewrite fails to find any more underscores. See this document for more.

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

资料来源与适用范围

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

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

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