I am trying to set up pretty urls with .htaccess
.
I got it to work, so both domain.com/contact/
works, and domain.com/contact.php
still also works. But now there are 2 urls in my domain, with the same content? Can this be avoided? So only domain.com/contact/
will work?
My .htaccess
file looks like this:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)([^./])$ %{REQUEST_URI}/ [L,R=301,NE]
RewriteRule ^contact/$ /contact.php
RewriteRule ^contact/$ /contact.php
You can either block direct access to /contact.php
or redirect /contact.php
back to /contact/
(the canonical URL). The later is generally preferred. For example:
RewriteRule ^contact\.php$ /contact/ [R=301,L]
RewriteRule ^contact/$ contact.php [END]
Note the addition of the END
flag (Apache 2.4+) on the existing rewrite to stop all further processing (preventing a redirect loop). I've also removed the slash prefix on the substitution string (preferable for internal rewrites).
Since you are rewriting to a file with the same basename as in the requested URL, you need to also make sure that MultiViews
(part of mod_negotiation) is disabled, otherwise /contact
(no slash) will also "work" and you could run into issues later (if you want to do more complex rewrites). Alter the Options
directive at the top of the file like so:
Options +FollowSymLinks -MultiViews
However, this isn't particularly scalable. Consider implementing a more generic /<php-file>
to /<php-file>.php
rewrite instead. (An exercise for the reader.)