Like mark says, require entry in combination with the no_results conditional
(i generally use dynamic=no and point the tag to the segment myself)
{exp:channel:entries channel="blog"
require_entry="yes" url_title="{segment_2}"
dynamic="no"}
<h2>{title}</h2>
{if no_results}
{redirect="404"}
{/if}
{/exp:channel:entries}
Handle list and detail: With a single catch-all template
At a later stage you can use add-ons and sophisticated tools, but a basic way to clean up things is a couple of simple(1) conditionals, for when you actually mean 404. e.g. when segment_2 is empty you want to show the list, but when no entries are found just show a message, not the 404. When an invalid url_title is provided (e.g. segment_2 not empty) only then redirect to 404
{exp:channel:entries channel="blog"
{if segment_2==""}limit="9"{/if}
{if segment_2!=""}require_entry="yes" url_title="{segment_2}"{/if}
dynamic="no"}
{if segment_2==""} (listview) {title} {/if}
{if segment_2!=""} (detailview) {title} {body} etc.{/if}
{if no_results}
{if segment_2==""}Sorry no entries we're found{/if}
{if segment_2!=""}{redirect="404"}{/if}
{/if}
{/exp:channel:entries}
Handle list and detail: With Sub-templates
Or split up in the index
template and have two templates to handle things separately:
{if segment_2==""}{embed="blog/listview"}{/if}
{if segment_2!=""}{embed="blog/detailview"}{/if}
Other thoughts
This gets ugly and sophisticated soon if you also want to catch archives (2014/10
), and categories (category/bada55
). At which point you can decide to use dedicated templates for each:
blog/
(list),blog/entry/...
(detail), blog/archive/...
, etc.
and then you have to decide if blog/entry/
(empty segment_3) should 404 or redirect to /blog/
or ... go with some add-on solution (switchee, conditionals, template partials with stash etc. or resource-router (tip, for, if you're into PHP and like to catch stuff early!)) Anyway, whichever you choose, you'll probably regret it later on also, for maintainability sake. So, in the end, it is all a matter of taste, tools and practice that you need to grow onto and into.
Happy coding...
(1) Simple conditionals has/had to do with parse order. The simple {if segment_x} conditional is parsed early. This is a topic by itself, which i leave to the reader to lookup.