You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过.htaccess仅将404错误永久重定向至指定子目录

Fix 404 Permanent Redirect to /old/ Directory with .htaccess

Hey there, I’ve got you covered on this 404 redirect issue. The key here is to target only requests that would result in a 404, then send a 301 permanent redirect (which Google explicitly recognizes for URL changes) to the corresponding path in your /old/ directory.

Here’s the exact .htaccess code you need to place in your website’s root directory:

RewriteEngine On

# Only redirect if the requested file or directory doesn't exist (i.e., would trigger 404)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Redirect to /old/[original requested path] with 301 permanent status
RewriteRule ^(.*)$ /old/$1 [L,R=301]

Let me break down what each part does so you understand:

  • RewriteEngine On: Enables Apache’s URL rewriting module—this is required for any rewrite rules to work.
  • RewriteCond %{REQUEST_FILENAME} !-f: Checks if the requested path is not an existing file (the ! negates the condition).
  • RewriteCond %{REQUEST_FILENAME} !-d: Checks if the requested path is not an existing directory. Together, these two conditions ensure we only redirect when the original request would throw a 404.
  • RewriteRule ^(.*)$ /old/$1 [L,R=301]:
    • ^(.*)$ captures the entire requested path (e.g., anyPage.html or some/subpage.php).
    • /old/$1 appends that captured path to the /old/ directory.
    • R=301 sends a permanent redirect status code—critical for Google to update its index and pass link equity to the new URL.
    • L tells Apache to stop processing further rules once this one is applied.

Important Notes:

  • Make sure your Apache server is configured to allow .htaccess files (check that AllowOverride All is set in your virtual host config for your website directory).
  • When testing, clear your browser cache first—301 redirects are cached aggressively, so old cache might make it look like the rule isn’t working.
  • If you have other rewrite rules in your .htaccess, place this rule before them to ensure it takes priority for 404 cases.

内容的提问来源于stack exchange,提问作者Jens Kirk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:37:43