.htaccess Redirect if smarty file .tpl doesn't exists

Viewed 25

I'm trying to do a short URL for my web built with Smarty. and I want to redirect to a 404 page if a smarty .tpl page doesn't exist.

Here is my .htaccess file

RewriteEngine on
RewriteBase /
Options +FollowSymLinks
Options -MultiViews
Options -Indexes
DirectorySlash Off

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\/?$ index.php?page=$1 [QSA,NC,L]

ErrorDocument 404 /sources/404.php

My root is

root
    .htaccess
    index.php
    sources
        404.php
    templates
        index.tpl
        acc.tpl

index.php

// Load Smarty library
require('smarty-4.2.0/libs/Smarty.class.php');
$smarty = new Smarty();

$smarty->setTemplateDir('templates');
$smarty->setCompileDir('templates_c');
$smarty->setCacheDir('cache');
$smarty->setConfigDir('config');

// Get page
$page = (isset($_GET['page'])) ? $_GET['page'] : 'index';

// Load PHP script for page
if (file_exists('sources/'.$page.'.php'))
    require_once('sources/'.$page.'.php');

$smarty->display($page.'.tpl');

Now when I go to site.com it works fine, also when I go to site.com/acc it redirects to site.com/templates/acc.tpl

but when I'm trying to go to site.com/acc1 which acc1.tpl doesn't exist in templates, smarty throws an error instead of getting an error 404 page.

The short question is, how do I check if there is file.tpl in templates by short URL and redirect to a 404 page if doesn't exist before the main redirect to index.php?page=FILE ?

something like

RewriteCond templates/%{REQUEST_URI} -f
RewriteRule ^(.*)\/?$ index.php?page=$1 [QSA,NC,L]
1 Answers

I did it by

RewriteCond %{DOCUMENT_ROOT}/templates/$1\.tpl -f
RewriteRule ^([\w\-.\s]+)$ index.php?page=$1 [QSA,NC,L]
Related