使用 apache rewrite 重写动态 url

发布于 2025-01-14 19:10:17 字数 364 浏览 3 评论 0原文

我的 html 内容中有一个锚标记,如下所示 class="list-content" href="/abcd/test.html"。 这在我的 html 的很多地方都有一些结果的列表。 我需要通过附加前缀来附加“href”中的所有这些 URL。

例如: /abcd/test.html 应该动态更改为 newprefix/abcd/test.html

如果我有另一个像 /xyz/some.html 那么这应该更改为 newprefix/xyz/some.html

我已经在互联网上探索了不同的解决方案,但我还没有找到适合我的问题的东西。

I have a anchor tag in my html content like this class="list-content" href="/abcd/test.html".
and this is in a lot of places in my html for a list of some results.
I need to append all these URLs that are in "href" by appending a prefix.

For example: /abcd/test.html should be dynamically changed as newprefix/abcd/test.html

If i have another one like /xyz/some.html then this should be changed as newprefix/xyz/some.html

I have explored different solutions over the internet and I have not found something that would fit my problem.

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

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

发布评论

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

评论(1

墨离汐 2025-01-21 19:10:17

要实现外部重定向以在这些请求前面添加 /newprefix,您可以在根 .htaccess (或服务器配置)顶部附近执行类似以下操作。

例如:

RewriteEngine On

RewriteRule ^[^/]+/[^./]+\.html$ /newprefix/$0 [R=302,L]

上面的代码会将 /abcd/test.html/xyz/some.html 的请求重定向到 /newprefix/abcd/test.html 和 /newprefix/xyz/some.html 。任何与模式 //.html 匹配的内容。

$0 是一个反向引用,其中包含与 RewriteRule 模式 匹配的 URL 路径。

请注意,这不是“url 重写”,因为您在评论中声明您不想向用户“隐藏”URL 的 /newprefix 部分。因此,如果您打算使用 Apache / mod_rewrite (如标记的),外部重定向是唯一的解决方案。

旁白:这对于 SEO、您的用户或您的服务器来说并不是特别好,因为用户每次点击您的一个链接时都会被外部重定向,这可能会使到达您服务器的请求数量增加一倍,并减慢您的用户速度。

To implement an external redirect to prepend /newprefix to these requests you could do something like the following near the top of the root .htaccess (or server config).

For example:

RewriteEngine On

RewriteRule ^[^/]+/[^./]+\.html$ /newprefix/$0 [R=302,L]

The above will redirect requests for /abcd/test.html or /xyz/some.html to /newprefix/abcd/test.html and /newprefix/xyz/some.html respectively. Anything that matches the pattern /<something>/<file>.html.

$0 is a backreference that contains the URL-path that is matched by the RewriteRule pattern.

Note that this is not "url-rewriting" since you stated in comments that you do not want to "hide" the /newprefix part of the URL from your users. An external redirect is therefore the only solution if you are intending to use Apache / mod_rewrite (as tagged).

Aside: This is not particularly good for SEO, your users or your server since the user is externally redirected everytime they click one of your links, potentially doubling the number of requests that hit your server and slowing your users.

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