Search code examples
.htaccesspretty-urls

"Pretty" URLs Not Working


I'm trying to remove the ".php" extension from the URLs of a site using this code (which I admit I copy/pasted from other questions here) in the .htaccess file:

RewriteEngine on
Options +FollowSymLinks    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Other lines of the .htaccess file do work, for instance, I have an error redirect and:

RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

So, I know the .htaccess file is in service in general.

I don't know what could go wrong in this area, so I'm not sure where to begin troubleshooting. Does anyone have pointers?

Thanks in advance.


Solution

  • Given that your domain account is /home/youraccount/public_html, your .htaccess would be inside the public_html folder with the following content:

    Options +FollowSymLinks -MultiViews
    
    RewriteEngine on
    RewriteBase /
    
    # First we redirect the www to non-www
    RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
    RewriteRule ^/?(.*)$ http://domain.com/$1 [R=301,L]
    
    # now we redirect phpless URLs internally to the php
    # if folder does not exist
    RewriteCond %{REQUEST_FILENAME} !-d
    # but the file exists and ends with .php
    RewriteCond %{REQUEST_FILENAME}\.php -f
    # redirect to name.php
    RewriteRule ^([^/]+)/?$ $1.php [L]
    

    NOTE: If you have more rules this may conflict so I would have to look at the rest of your rule but basically the above should work as expected.

    You will be able to access both:

    domain.com/index
    

    and

    domain.com/index/
    

    And it would redirect to your file index.php.