How to make unpublished nodes "404 Not Found" instead of "Access Denied" for those without access

Last updated on 20/02/2016
/**
 * Implements hook_page_delivery_callback_alter().
 */
function mymodule_page_delivery_callback_alter(&$delivery_callback) {
  if ($router_item = menu_get_item()) {
    // Check for a node using the normal node_access callback
    if (isset($router_item['access_callback']) && $router_item['access_callback'] == 'node_access') {
      // Check for what would normally be an access denied
      if (empty($router_item['access'])) {
        // Check the status is unpublished
        if ($node = node_load($router_item['original_map']['1'])) {
          if (empty($node->status)) {
            $delivery_callback = 'mymodule_deliver_page_not_found';
          }
        }
      }
    }
  }
}
 
/**
 * Callback for mymodule_page_delivery_callback_alter()
 * to show the page not found content.
 */
function mymodule_deliver_page_not_found() {
  drupal_deliver_html_page(MENU_NOT_FOUND);
}