Here's what your .htaccess
should look like:
RewriteEngine On
# Remove www.
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
# Remove file extensions, add a trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
This is a really good reference article about removing file extensions fro URLs. Just remember, for this to work, you must reference the non-extension version in all of your links e.g. <a href="about">About</a>
, not <a href="about.php">About</a>
While you're doing .htaccess
things, I might also recommend adding in the following snippets. The first two are concerned with website speed, the second is for a custom 404 page, and the third is for forcing UTF-8
(so you don't have to declare it in your HTML).
# Expires caching (Caching static files for longer drastically improves performance, you might even want to put even more aggressive times)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
# Gzip
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# 404 Page
ErrorDocument 404 /404.php
# Force UTF-8
AddDefaultCharset utf-8
I wrote about this in a blog post on CodePen, if you're interested.
HTML BP has an insane 700+ line .htaccess that you can see for some cool tricks.