.htaccess 中的 URL 重写出现问题

发布于 2024-12-27 22:18:21 字数 613 浏览 1 评论 0原文

我的 .htaccess 文件如下所示:

RewriteEngine On
RewriteRule ^articles/(\d+)*$ ./articles.php?id=$1

因此,如果请求 URL foo.com/articles/123,控制权将转移到 articles.php?id= 123..

但是,如果请求的 URL 是:

foo.com/articles/123/

或者

foo.com/articles/123/whatever

我收到“404 Not Found”响应。

在所有这些情况下我想调用articles.php?id=123。因此,如果 URL 以 foo.com/articles/[digits]... 开头,无论数字后面还有什么其他字符,我都想执行 articles.php?id=[数字]。 (URL 的其余部分将被丢弃。)

我必须如何更改正则表达式才能实现此目的?

My .htaccess file looks like this:

RewriteEngine On
RewriteRule ^articles/(\d+)*$ ./articles.php?id=$1

So, if the URL foo.com/articles/123 is requested, control is transferred to articles.php?id=123.

However, if the requested URL is:

foo.com/articles/123/

or

foo.com/articles/123/whatever

I get a "404 Not Found" response.

I would like to call articles.php?id=123 in all these cases. So, if the URL starts with foo.com/articles/[digits]... no matter what other characters follow the digits, I would like to execute articles.php?id=[digits]. (The rest of the URL is discarded.)

How do I have to change the regular expression in order to achieve this?

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

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

发布评论

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

评论(2

┈┾☆殇 2025-01-03 22:18:21

只是不要寻找结局:

RewriteRule ^articles/(\d+) ./articles.php?id=$1

Just don't look for the end:

RewriteRule ^articles/(\d+) ./articles.php?id=$1
¢蛋碎的人ぎ生 2025-01-03 22:18:21

您确实需要允许尾随 /

RewriteRule ^articles/(\d+)/?$

\d+ 仅匹配小数。并且 $ 将不允许超出末尾的匹配。

如果您还需要尾随标识符,那么您也需要允许它们。那么最好使匹配不特定:

RewriteRule ^articles/(.+)$

这里 .+ 几乎匹配任何内容。

但如果您想将数字 id 分开,请结合这两个选项:

RewriteRule ^articles/(\d+)(/.*)?$   ./articles.php?id=$1

You do need to allow the trailing / with:

RewriteRule ^articles/(\d+)/?$

The \d+ will only match decimals. And the $ would disallow matches beyond the end.

If you also need trailing identifiers, then you need to allow them too. Then it might be best to make the match unspecific:

RewriteRule ^articles/(.+)$

Here .+ matches virtually anything.

But if you want to keep the numeric id separate then combine those two options:

RewriteRule ^articles/(\d+)(/.*)?$   ./articles.php?id=$1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文