Search code examples
phpmod-rewriteforum

How to redirect to .php file if exists and another if it doesn't


I've only just written a forum in PHP. In my database, under my posts table and my categories table, I have a field called 'slug' for the url.

I have urls like /html for my HTML category and /html/test for a post named test under the HTML category.

But I also want urls like /signin which redirect to signin.php.

Is there a rewrite condition I can use that if I go to, for example /something, it will chech if something.php exists. If it does, it will show the content of something.php, else it will show category.php?cat_id=something?


Solution

  • Is there a rewrite condition I can use that if I go to, for example /something, it will chech if something.php exists. If it does, it will show the content of something.php, else it will show category.php?cat_id=something?

    Try:

    RewriteEngine On
    
    # exclude legit requests
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # check if requests is pointing to a php file
    RewriteCond %{REQUEST_URI} ^(.*?)/?$
    RewriteCond %{DOCUMENT_ROOT}/%1.php -f
    RewriteRule ^ /%1.php [L]
    
    # otherwise, serve the category (also need to exclude legit requests)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /category.php?cat_id=$1 [L,QSA]