"ErrorDocument 404 in .htaccess is incompatible with RewriteRule, resulting in functional failure"
P粉320361201
P粉320361201 2024-01-10 16:56:14
0
1
343

.htaccess ErrorDocument 404 No redirection when using rewrite rules. A 500 Internal Server Error occurs.

Without RewriteRule, ErrorDocument works normally.

My code

RewriteEngine On 
   <IfModule mod_rewrite.c>
   RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ /stores/  [NC,L]
   ErrorDocument 404 /404.html
  </IfModule>

P粉320361201
P粉320361201

reply all(1)
P粉605233764

The "problem" with this rule is that if you request a file that doesn't exist, and the file doesn't exist in the /subdirectory/ subdirectory, then it will cause an infinite rewrite loop (hence the 500 you see Internal Server Error) because it attempts the following rewrite:

  • /not-exists (initial request)
  • /stores/not-exists (first rewrite)
  • /stores/stores/not-exists (second rewrite)
  • /stores/stores/stores/not-exists (third rewrite)
  • etc.

You didn't actually specify what you were trying to achieve, but I'm assuming /stores is a "hidden" subdirectory and you intended to overwrite to the actual files in the /stores subdirectory. This is the only way such a rule will work with the ErrorDocument 404 directive defined in Apache.

Therefore, when rewriting to the /stores subdirectory, you need to first check whether the request will be mapped to an actual file before issuing the rewrite. This way, any request for a file that does not exist and is not mapped to the /stores subdirectory will be passed to the Apache-defined 404 ErrorDocument.

For example, try using the following code:

ErrorDocument 404 /404.html

RewriteEngine On 

# 如果该目录中存在文件,则将请求重写到“/stores”目录
RewriteCond %{DOCUMENT_ROOT}/stores/ -f
RewriteRule (.+) stores/ [L]

# (可选)将根目录的请求重写为“/stores/”
RewriteRule ^$ stores/ [L]

No need for <IfModule> container (but you put the RewriteEngine directive outside this container, which makes no sense).

If the .htaccess file is located in the document root directory, the RewriteBase directive is not required.

Structurally, it is best to define ErrorDocument first.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template