Search code examples
apache.htaccessmod-rewriteurl-rewritingfriendly-url

mod_rewrite: Error 500 triggered when URI contains an existing file without extension followed by /whatever when using REQUEST_FILENAME


What I want to do

If the requested resource in the URL has no extension and a file name matches the resource, use mod_rewrite to service that file. Otherwise, trigger error 404.

E.g. request is /foo and I have foo.html then I should service foo.html

Test case

I have a file called foo.html

  • If the user requests URL website.com/foo it works fine -> displays the content of foo.html
  • If the user requests URL website.com/foo.html it works fine -> displays the content of foo.html
  • If the user requests URL website.com/foo.html/bar it works fine -> 404
  • If the user requests URL website.com/foo/bar it does NOT work => ERROR 500 instead of 404

What I tried

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]

My understanding so far

My best bet after browsing SO and the doc of Apache is this line:

Depending on the value of AcceptPathInfo, the server may have only used some leading components of the REQUEST_URI to map the request to a file.

Source

Am I correct in assuming this is the cause of the error ? REQUEST_FILENAME = foo instead of /foo/bar ? Hard to tell without logs.

If I am correct what would be an alternative ? Can I check if REQUEST_FILENAME ends with REQUEST_URI ? That would tell me this behavior was triggered.

Additional information

  • I am renting some basic web hosting service, I don't think I have access to httpd.conf. I looked for it in the file system and could not find it
  • I didn't find any logs of mod_rewrite and I am not sure it is even turned on (need to add the trace level in the httpd.conf)
  • I don't really know what the webserver nor the version are. I assume it is Apache because it uses .htaccess files
  • I sent a mail to the company to ask for more details. Will update it once I have a reply

Logs

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at [email] to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Solution

  • I confirm. Issue was REQUEST_FILENAME not being reliable due to Apache configuration. And because it is a shared hosting I cannot modify the option.

    So I had to resort to ugly hardcoding. I basically fake REQUEST_FILENAME I really wanted by using REQUEST_URI, this way I test for the file I really am interested in.

    # Hide html
    RewriteCond /path_to/public_html%{REQUEST_URI}\.html -f
    RewriteRule ^(.*)$ $1.html [NC,L,E=LOOP:1]