How to replace underscore to dash with Nginx

前端 未结 3 1924
日久生厌
日久生厌 2020-11-30 14:30

I\'m using Nginx for the first time ever, and got basically no knowledge of it.

I need to replace \"_\" with \"-\" in 100+ URL. I figured there must be an easy way t

3条回答
  •  隐瞒了意图╮
    2020-11-30 15:23

    Both existing answers to this question from 2013-04 and 2015 are rather suboptimal and ugly — one relies on too much copy-paste and has unclear error handling/reporting, and another one involves having an undefined number of unnecessary 301 Moved interactions for the client to handle.

    There's a better way, hidden in plain sight at a QA pair from 2013-02 — only a couple of months prior to this very question from 2013-04! It involves relying on the last parameter for the http://nginx.org/r/rewrite directive, which will cause nginx to stop processing the rewrite directives should one with last result in a match, and go back in search of an appropriate "new" location per the modified $uri, causing an internal redirect loop within nginx for up to 10 times (e.g., 10 internal redirects, as per http://nginx.org/r/internal), recording a 500 Internal Server Error if you exceed the limit of 10 cycles.

    In a sense, this answer is similar to the original one, it's just that you get an extra factor of 10 for free, resulting in fewer copy-paste requirements.

    # Replace maximum of 3 or 1 underscores per internal redirect,
    # produce 500 Internal Server Error after 10 internal redirects, 
    # supporting at least 28 underscores (9*3 + 1*1) and at most 30 (10*3).
    location ~ _ {
        rewrite "^([^_]*)_([^_]*)_([^_]*)_(.*)$" $1-$2-$3-$4 last;
        rewrite "^([^_]*)_(.+)$" $1-$2 last;
        return 301 $uri;
    }
    

提交回复
热议问题