Yes, I know that this question was asked multiple times already and is answered, but I will give a little more comprehensive answer based on my experience.
Here is the .htaccess code snippet that will help you:
# Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}"https://stackoverflow.com/"#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)/$ $1.php
# End of Apache Rewrite Rules
</IfModule>
I want to stress some important things here for everybody’s reference:
- This code snippet doesn’t remove entry scripts from url (such as
index.php
used by many PHP frameworks) - It only removes
.php
extension, if you want to remove other extension as well (e.g..html
), copy and paste 3rd block and replacephp
with other extension. - Don’t forget to also remove extension from anchors (links) href.