Why are URLs with non-existing subdomains not triggering an error 404? One of my websites ignores random subdomains. The site doesn't have any subdomains but it will happily accept URLs such as fjiddifjdskdjf.example.com or dsfkljsdflsdjfds.example.com.
In both cases, it will display the home page. Similarly, I can log in at sfkjsdidisfdj.example.com/user.

At first, I suspected the problem was with a .htaccess file I put in the root directory. The file is used to redirect URLs that changed when I redesigned the website. It's got entries like this.

RedirectMatch 301 ^/2012/06/$ /blog/201206


However, after renaming the file, it's still accepting these odd, random subdomains.

I've also checked another Drupal site I maintain. On that site, entering a non-existent subdomain results in an 404 error. I've compared both sites' standard .htaccess files and they're identical. Both sites use the same (shared) hosting package, which should rule out differences in how the server has been configured.

Why URLs with non-existing subdomains don't trigger an error? How can I correct this behaviour?
While you have stated that hosting is the same for both your sites it is most probably that this is either a server configuration issue or a DNS configuration issue rather than a Drupal setting issue.
In .htaccess the following catches 'wildcard' subdomains 

RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]


In Apache configuration the following catches 'wildcard' subdomains

&lt;VirtualHost *:80&gt;
        ServerAlias *.example.com
        Redirect 301 / http://www.example.com
&lt;/VirtualHost&gt;


In Nginx confiuration the following catches 'wildcard' subdomains
(as you are using .htaccess you are obviously not using Nginx but for completeness..)

server {
  server_name *.example.com;
  return 301 $scheme://example.com$request_uri;
}

server {
  server_name www.example.com;

  #add in further directives to serve your content
}


These are the most common configurations that will catch wildcard sub-domains on the server.

It is possible to do redirects in settings.php also but not for wildcard.

The other possibility is that the issue is at the DNS entry. You may have set up a wildcard sub-domain which may also be known as a catch-all-subdomain. 

The layout of this will be determined by your DNS provider.
This Drupal guide illustrates how it would be acheived on cPanel: https://www.drupal.org/node/1068894