.htaccess to redirect to 404 Error Message rather than empty html.php page

Using a song database as an example, I am using the below code:-

.htaccess (placed in root directory, with 404.html.php in the ‘includes’ directory; ‘includes’ directory is also located in the root directory; and I am running server on Apache)

ErrorDocument 404 /includes/404.html.php
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^song/([0-9]*)/([-()a-z0-9]*)$ song/?song_id=$1&song_url=$2 [L,QSA]
RewriteRule ^artist/([-()a-z0-9]*)$ artist/?artist_url=$1 [L,QSA]

This outputs, i.e.:-

songdatabase/song/47/she-loves-you
songdatabase/artist/the-beatles

With song, both ‘song_id’ (unique) and ‘song_url’ (not unique) must be matched (I could just use ‘song_id’ to call it but I want the song title to be displayed in the URL); and with artist only ‘artist_url’ (unique) must be matched.

The 404 works, i.e. when entering a URL such as:-

songdatabase/home/jkehfkudsf

However, entering the below examples (i.e. URLs that pass non-existing variable info), instead of receiving the 404 Error page, I receive the template html.php page for song or artist respectively, just without any information displayed as obviously no existing variable info is passed via the URL.

songdatabase/song/7638384/
songdatabase/song/47/
songdatabase/song/47/jkfhsdudjkbvd
songdatabase/artist/dnfksjdhdkchd

Is there any way of making any such instances automatically redirect to the 404 page?

I could conduct a check at the start of the respective indexes for song and artist whether there is a match and if not then redirect to 404, else continue with the code.

But I am sure there must be a way that this can be done more simply and cleanly within the .htaccess file (I think using mod_write / RewriteCond), right?

Thanks!

How would htaccess know a song/artist doesnt exist before your script queries the database?

Sorry, I’ve only recently found out about .htaccess and am still learning about its capabilities and limitations. Would you suggest best solution is to check for existing song/artist at the start of each index and redirect to 404 if applicable, else continue with code?

That would be exactly what i would do.

songdatabase/artist/dnfksjdhdkchd

This could imply instances such as a recently removed artist, or a slightly malformed url (accidentally truncated when passed from another website for example).

In the case of a partially correct request I would want to keep the user engaged … maybe show most popular artists, or do attempt a search using … where artist_name LIKE “dnfksjdhdkchd%” before blandly issuing a 404.

2c

That’s a good idea. Given I’ll now be doing the check at the start of each directory’s index, if there’s no match then I can redirect to a specific page for each (i.e. popular songs for incorrect song URLs, popular artists for incorrect artist URLs, etc.)

Thanks!