.htaccess 删除导致内部服务器错误的 URL 路径段

.htaccess remove URL path segments that are causing an Internal Server Error

下面的 .htaccess 如果 URL 是这样的,下面的重写似乎工作正常:example.com/news/post-1

RewriteRule ^/?news/([^/]+)/?$ article.php?slug= [L,QSA]

但是,如果 URLs 有更多参数,例如:example.com/news/post-1/comment-page-1(URLs 来自另一个版本的网站)我将收到 500 Internal Server Error。

如何让它重定向到相关的 post 而不是 500 内部服务器错误?

if the URLs have more parameters, something like: example.com/news/post-1/comment-page-1 (URLs from another version of the website) I will get a 500 Internal Server Error.

500 错误是由您的 .htaccess 文件中的 其他原因 引起的,因为您发布的指令不适用(如@CBroe 在评论中所述)。

因此,500 错误可能会通过修复导致此问题的任何指令来解决。

顺便说一句,这些是“路径段”,而不是“参数”。您可能会将它们视为脚本的参数,但在请求的 URL 中它们并非如此。

How I can make it redirect to the related post instead of 500 Internal Server Error?

如果您想通过将 /news/<slug>/<anything> 重定向到 /news/<slug>/ 来解决此问题,那么您可以在 [=12] 的 top 附近执行类似以下操作=] 文件,在现有重写之前:

# Remove additional path segments from the URL-path
RewriteRule ^(news/[^/]+/). / [R=302,L]

正则表达式上的点匹配最后一个斜杠后的单个字符,因此必须包含一个额外的路径段(至少)。

</code> 反向引用仅包含您感兴趣的 URL 路径部分(即 <code>/news/<slug>/)并重定向至此。

请注意,目前这是一个 302(临时)重定向。在确认其按预期工作后更改为 301(永久)重定向之前,请始终使用 302 进行测试以避免潜在的缓存问题。