Search code examples
.htaccessmod-rewritefriendly-urltrailing-slashpretty-urls

.htaccess pretty URL's excluding index.php and adding trailing / to the end


Ok, I've fought with it for hours. I have 3 different .htaccess scripts which do what I need, but I'm unable to mix them together.

  1. Make a pretty url from (example.com/gallery.php -> example.com/gallery)

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9]+)$ $1.php
    
  2. The script from #1 though forwards example.com/index.php to example.com/index, so this code removes index.php so example.com/index.php -> example.com

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?$1 [L,QSA]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
    RewriteRule ^ /%1 [R=301,L]
    
  3. The script should add a trailing slash so example.com/gallery -> example.com/gallery/

    # invoke rewrite engine
    RewriteEngine On
    RewriteBase /~new/
    
    # add trailing slash if missing
    rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]
    

Can someone help me to combine those 3 scripts into one universal pretty URL scripts


Solution

  • add these directives to .htaccess in the root directory of your website

    Options +FollowSymLinks
    RewriteEngine On
    
    # add trailing slash
    
    RewriteCond %{REQUEST_URI} !(/$|\.) 
    RewriteRule (.*) %{REQUEST_URI}/ [R=301,L] 
    
    # rewrite gallery/ to gallery.php
    
    RewriteCond %{REQUEST_URI} /$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ $1.php [L]
    
    # redirect example.com/index.php to example.com/
    
    RewriteCond %{REQUEST_URI} index\.php$
    RewriteRule ^(.*)index\.php$ /$1/ [R=301,L]