Vasyl Yaremchuk

How to add each own 404 page to each section of the Drupal 7 site.

Several days ago I have following task:

there is a site with URLs content structure:

section-1/title-1
section-1/title-2
section-1/title-3

section-n/title-1
section-n/title-2

etc.

Task, to provide the ability of separate 404 page for each section of the site,
that is
section-1/404

section-n/404

Of course, we can use Rules API to set complex rules but there is more simple way to solve this problem.

I think arg() function helps us. See http://api.drupal.org/api/drupal/includes%21path.inc/function/arg/6
Without any argument arg() returns the array of the current path components.
If it will be correct node alias arg() returns following array:

[0] = 'node'
[1] = some node id

in the case of wrong path it returns for example:

[0] = 'section-1'
[1] = 'wrong-title'

Let's create simple "section_404" module.

<?php function section_404_init() { $args = arg(); if($args[0] != 'node' && $args[0] != 'admin') // in the case if we are going to use not simple node content but views etc. the condition can be more complex drupal_goto($args[0] . '/404'); } ?>

As was indicated in the comment in the code the real condition that you should use on production site should be more complex.