Search code examples
.htaccessforwardslash

.htaccess folder look-alike viewing php file with and without forward slash


I'm trying to use .htaccess to make my php files look a little neater in the URL.


Here's what I have:

www.domain.com/file.php

Here's how I would like it to be accessed (and how it should be shown in the URL:

www.domain.com/file OR www.domain.com/file/


I have found sites that do this, so I know it's possible however, this is the best I can come up with within my .htaccess file:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^titaniumwebdesigns.com$ [NC]
RewriteRule ^(.*)$ http://www.titaniumwebdesigns.com/$1 [R=301,L]
RewriteRule ^(.*)\/$ $1.php [NC]

The only problem is, it doesn't work with www.example.com/page as it redirects to a folder whereas www.example.com/page/ successfully redirects to www.example.com/page.php using the extra forward slash.

The other parts just add in the http://www. to look neater. Is there more to it than just the .htaccess file?


Solution

  • I'm assuming here that you have a file called page.php but also a folder called page? If so, the easiest way will be just write a routing file which will redirect, then you can use this code:

    RewriteRule ^router\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . /router.php [L]
    

    Then just set up rules in the PHP to test what the $_SERVER['REQUEST_URI'] is returning, then include the files.