Trying to redirect with and without trailing slash

8,683

Please use bellow syntax

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !example.php
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://example.com/$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f makes shure that files that are existing will not get a slash added.

RewriteCond %{REQUEST_URI} !example.php exludes a sample url that shouldn’t be rewritten.

RewriteCond %{REQUEST_URI} !(.*)/$ finally fires when a urls doesn’t contain a trailing slash – this is all what we want. Now we need to redirect these url with the trailing slash:

RewriteRule ^(.*)$ http://example.com/$1/ [L,R=301] does the 301 redirect to the url with the trailing slash appended for us. You should replace domain.com with your url.

Share:
8,683

Related videos on Youtube

Guerrilla
Author by

Guerrilla

Updated on September 18, 2022

Comments

  • Guerrilla
    Guerrilla almost 2 years

    I have moved a blog to a subdomain and on the subdomain all the categories have changed so I want to do a list of 301 re-directs from old domain to subdomain (different hosting).

    The problem I am having is adding on the trailing slash so I don't have to list every URL twice.

    I tried this in /blog/.htaccess:

    RewriteEngine On
    
    #RewriteRule ^(.*)$ http://domain.com/blog/$1/ [L,R=301] 
    
    Redirect 301 /blog/test/ https://new.domain.com/test/
    Redirect 301 /blog/example/ https://new.domain.com/example/
    (etc...)
    

    This doesn't work though as the browser detects too many re-directs.

    What is the proper syntax here?

    I also tried:

    RedirectMatch /blog/test/?$ https://new.domain.com/test/ [L,R=301] 
    

    But that doesn't seem to work at all.

  • MrWhite
    MrWhite over 7 years
    Note that this only redirects that one specific URL (unlike the Redirect directive you had initially). For instance, this won't redirect /blog/test/something, if that is a concern?
  • Dennis Nolte
    Dennis Nolte almost 6 years
    you might want to add a bit of explanation why this syntax will work
  • sanjayparmar
    sanjayparmar almost 6 years
    Added description