如何用 Nginx 替换下划线以破折号 [英] How to replace underscore to dash with Nginx

查看:29
本文介绍了如何用 Nginx 替换下划线以破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次使用 Nginx,对它基本上一无所知.

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

我需要将 100 多个 URL 中的_"替换为-".我想一定有一种简单的方法可以用 Nginx 做到这一点,但在 Google 上找不到任何东西.

I need to replace "_" with "-" in 100+ URL. I figured there must be an easy way to do this with Nginx, but can't find anything on Google.

谢谢!

我的网址例如:http://www.mywebsite.com/this_category/page1.php

我需要把它变成:http://www.mywebsite.com/this-类别/page1.php

推荐答案

2013-04 和 2015 年对这个问题的现有答案都相当不理想和丑陋——一个依赖于太多的复制粘贴并且错误处理/报告不清楚,另一个涉及到客户端处理数量不确定的不必要的 301 Moved 交互.

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.

有更好的方法,隐藏在 2013 年的 QA 对中-02 — 仅在 2013-04 年提出的这个问题之前几个月!它涉及依赖 last 参数的 http://nginx.org/r/rewrite 指令,如果 last 结果匹配,这将导致 nginx 停止处理重写指令,并返回寻找适当的新"location 根据修改后的 $uri,导致 nginx 内最多 10 次的内部重定向循环(例如,10 次内部重定向,根据 http://nginx.org/r/internal),如果超过 10 个周期的限制,则记录 500 Internal Server Error.

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.

从某种意义上说,这个答案与原始答案相似,只是您免费获得了 10 倍的额外系数,从而减少了复制粘贴的要求.

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;
}

这篇关于如何用 Nginx 替换下划线以破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆