如何通过.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.htmlorsome/subpage.php)./old/$1appends that captured path to the/old/directory.R=301sends a permanent redirect status code—critical for Google to update its index and pass link equity to the new URL.Ltells Apache to stop processing further rules once this one is applied.
Important Notes:
- Make sure your Apache server is configured to allow
.htaccessfiles (check thatAllowOverride Allis 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
相关产品推荐
相关产品推荐

