使用.htaccess的两个不同的404文档

iugsix8n  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(79)

我在Apache Web服务器上有一个网站。我需要配置.htaccess,以便当您转到像example.com/non-existent_page这样的地址时,显示404.html页面,当您转到像example.com/ru/non-existent_page这样的地址时,显示ru/404.html页面。
这里解决了类似的问题:https://discourse.gohugo.io/t/404-pages-on-localhost-for-multilingual-site-failing/40568/2但对于本地服务器Hugo:

[[redirects]]
from = '/ru/**'
to = '/ru/404.html'
status = 404

[[redirects]]  # Default lang, should be last.
from = '/**'
to = '/404.html'
status = 404

字符串
我的.htaccess的当前版本是这样的:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /404.html [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ru/(.*)$ /ru/404.html [L]


example.com/ru/testexample.com/test重定向到404.html的英文版本,即到位于遗址根部的那个

nr7wwzry

nr7wwzry1#

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /404.html [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ru/(.*)$ /ru/404.html [L]

字符串
你只需要改变这些规则的顺序,让更具体的规则排在第一位。目前,第一条规则将不存在的 * 任何内容 *(包括以/ru/开头的URL)重写为/404.html,第二条规则实际上被忽略。
换句话说:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ru/. /ru/404.html [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.html [L]


(我稍微简化了正则表达式。捕获子模式不是必需的,也不需要匹配目录本身,因为第二个条件只会失败。)

改用ErrorDocument

但是,上面的代码不会提供404 HTTP状态,除非服务器端脚本(在.html文件中?)设置此。考虑使用ErrorDocument指令(不需要mod_rewrite),它将指示Apache本身以正确的404 HTTP状态进行响应。举例来说:

ErrorDocument 404 /404.html
<If "%{REQUEST_URI} =~ m#^/ru/#">
    ErrorDocument 404 /ru/404.html
</If>


上面的代码将404错误文档设置为/404.html,但是当请求的URL路径以/ru/开头时,会覆盖这个错误文档。这种方法的主要优点是Apache将设置适当的HTTP响应状态。
或者,有两个.htaccess文件。一个位于根目录中,用于设置ErrorDocument 404 /404.html,另一个位于/ru/目录中,用于设置ErrorDocument 404 /ru/404.html。后者将覆盖前者。

相关问题