How to programmaticaly serve a 404 in template.php I have the previous logic to feed a View in MY_TEMPLATE_preprocess_page.
When the URL, where I have some paremeters passed in a user friendly way, does not exist (the parameters are not correct), I am serving a "Product not found message". However, I think it is more correct, for SEO purposes, to serve a 404-Not Found page, with the correct HTTP Headers. I am trying to achive this with drupal_not_found but the page takes a minute to load and finally shows a blank screen.

Where should I put the logic and the drupal_not_found call? Must I move it to my custom module, in MY_MODULE_init() or something? I need to access $node-&gt;nid.

Example:

Correct : http://www.example.com/products/shoes

Wrong (404) : http://www.example.com/products/dsfsdfswerweipwr
My personal advice is to return the "No results found" message from Views instead of issue a 404. Why? Because if you ever wind up adding products or changing the name of a product, what used to be a 404 is not anymore. I feel like from an SEO perspective you would have an uphill battle. Anyway.

One way to do this would be from a custom module. Do not do it in template.php.

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(&amp;$view) {
   if ($view-&gt;name == 'myview' &amp;&amp; some_other_conditions) {
     if (empty($view-&gt;result)) {
       drupal_add_http_header('Status', '404 Not Found');
       drupal_not_found();
       drupal_exit();
     }
  }
}


Bonus, Drupal 8:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(ViewExecutable $view) {
   if ($view-&gt;id() == 'myview' &amp;&amp; some_other_conditions) {
     if (empty($view-&gt;result)) {
       throw new NotFoundHttpException();
     }
  }
}


Is the view generating the page at products/%? Why do you need to know the $node-&gt;nid?