Home  >  Q&A  >  body text

"ErrorDocument 404 in .htaccess is incompatible with RewriteRule, resulting in functional failure"

.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粉320361201P粉320361201306 days ago300

reply all(1)I'll reply

  • P粉605233764

    P粉6052337642024-01-11 09:26:16

    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.

    reply
    0
  • Cancelreply