andygout — 2013-01-15T08:35:03-05:00 — #1
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
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.:-
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:-
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.
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?
starlion — 2013-01-15T08:49:41-05:00 — #2
How would htaccess know a song/artist doesnt exist before your script queries the database?
andygout — 2013-01-15T08:57:39-05:00 — #3
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?
starlion — 2013-01-15T09:01:09-05:00 — #4
That would be exactly what i would do.
cups — 2013-01-15T10:19:08-05:00 — #5
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.
andygout — 2013-01-16T08:09:15-05:00 — #6
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.)