htaccess:重定向301图像如果不存在

发布于 2025-02-12 04:38:47 字数 245 浏览 1 评论 0原文

在我的htaccess文件中,我应该确保如果不存在“特定图像”的资源,则必须进行301重定向,并具有不同的扩展名。

我尝试更好地解释自己:

图像:test.webp

如果不存在,它必须推迟:

test.jpg

可以做这样的事情吗? 如果我不编写我的代码示例,我深表歉意,但我真的不知道如何在我的htaccess中处理它。

谢谢

in my htaccess file I should make sure that if a resource "a specific image" is not present it must do a 301 redirect with a different extension.

I try to explain myself better:

image: test.webp

if it does not exist, it must postpone:

test.jpg

Can such a thing be done?
I apologize if I don't write an example of my code, but I really don't know just how to handle it in my htaccess.

Thank you

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

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

发布评论

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

评论(1

软糖 2025-02-19 04:38:47

您可以在.htaccess文件的顶部使用mod_rewrite来执行此操作:

RewriteEngine On

# Redirect "webp" images that do not exist to "jpg"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

对于不存在的任何请求。文件,但带有.jpg扩展名。例如。 /foo/bar/does-not-exist.webp被重定向到/foo/bar/does-not-exist.jpg

还要检查目标.jpg是否存在(重定向之前),您可以添加其他条件。例如:

# Check that corresponding ".jpg" file exists before redirecting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.jpg -f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

但是,我会质疑外部3XX重定向是否真的是这里使用的正确方法。如果您有许多这样的文件,这可能是低效/慢的。例如。触发内部重写?例如,请参见我的答案以下问题:

You can do this using mod_rewrite at the top of your .htaccess file:

RewriteEngine On

# Redirect "webp" images that do not exist to "jpg"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

For any request to a .webp file that does not exist, a 301 redirect is triggered to the same file but with a .jpg extension. eg. /foo/bar/does-not-exist.webp is redirected to /foo/bar/does-not-exist.jpg.

To also check that the target .jpg exists (before redirecting) you can add an additional condition. For example:

# Check that corresponding ".jpg" file exists before redirecting
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.jpg -f
RewriteRule ^(.+)\.webp$ /$1.jpg [R=301,L]

However, I would question whether an external 3xx redirect is really the correct thing to be using here. This can be inefficient/slow if you have many such files. eg. Trigger an internal rewrite instead? For example, see my answer to the following question:

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