使用 mod_rewrite 时是否必须转义正斜杠?

发布于 2024-09-16 17:04:30 字数 859 浏览 3 评论 0原文

关于向 RewriteRule 或 RewriteCond 提供正则表达式时的正斜杠“/”,或者特别是与 .htaccess 相关的任何其他内容,是否需要转义正斜杠?

这是我想要实现的目标的示例

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region\/|regions\/)$ regions [R=301,L]
RewriteRule ^(county|county\/|counties\/)$ counties [R=301,L]
RewriteRule ^(city|city\/|cities\/)$ cities [R=301,L]

上面的工作正常,并且当我删除反斜杠时它继续工作正常,如下所示

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region/|regions/)$ regions [R=301,L]
RewriteRule ^(county|county/|counties/)$ counties [R=301,L]
RewriteRule ^(city|city/|cities/)$ cities [R=301,L]

哪个是正确的方法?他们俩都错了吗? 是否有任何特殊原因应该转义或不应该转义正斜杠?

我的猜测是,据我所知,正斜杠不需要转义,因为它不是特殊字符。但我只是想确定一下。

如果您想知道这段代码的意义,它将城市、县和地区(带或不带正斜杠)重定向为其复数形式。此外,如果复数有正斜杠,它会删除正斜杠。

With regards to the forward slash "/" when giving a regex to RewriteRule or RewriteCond, or anything else related to .htaccess in particular, is there a need to escape the forward slash?

Here is an example of what I am trying to achieve

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region\/|regions\/)$ regions [R=301,L]
RewriteRule ^(county|county\/|counties\/)$ counties [R=301,L]
RewriteRule ^(city|city\/|cities\/)$ cities [R=301,L]

The above works fine, and it continues to work fine when I remove the backslashes as shown below

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region/|regions/)$ regions [R=301,L]
RewriteRule ^(county|county/|counties/)$ counties [R=301,L]
RewriteRule ^(city|city/|cities/)$ cities [R=301,L]

Which one is the correct way? Are they both wrong?
Is there any special reason the forward slash should be escaped, or shouldn't?

My guess is that the forward slash does not need to be escaped because it isn't a special character, as far as I know. But I just want to be sure.

In case you're wondering the point of this code, it redirects city, county, and region (with or without a forward slash) to their plural equivalents. Furthermore if the plural has a forward slash it removes the forward slash.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

窗影残 2024-09-23 17:04:30

不,你不必逃避斜杠。正斜杠在正则表达式中没有任何特殊含义。

过去困扰我的一个常见字符是查询字符串中的 ?。那个你必须逃脱的人。

No, you do not have to escape slashes. Forward slashes don't have any special meaning in regular expressions.

The one common character that has bitten me in the past is ? in query strings. That one you do have to escape.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文