Search code examples
apache.htaccesshttp-redirectmod-rewritetrailing-slash

htaccess redirect nestings causes trouble - trailing slash needed


I have some rules in my htacces, everything by learning by doing with the help of stackoverflow and other sites. But now I wanted to add a rule for adding a trailing slash to urls without a suffix (to pretend duplicate content), the trouble starts - and a never ending loop occurs.

These are the rules i got in my htacces:

RewriteEngine on
RewriteBase /

# redirect urls without www. to url with www.
RewriteCond %{HTTP_HOST} ^domain\.de$
RewriteRule ^(.*)$ http://www.domain.de/$1 [L,R=301]

# hide the suffix of urls
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.html\ HTTP/
RewriteRule (.*).html$ /$1 [R=301,L]

# start redirect everything to the subfolder
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.de [NC]
# except these folders: 
RewriteCond %{REQUEST_URI} !^/downloads [NC]
RewriteCond %{REQUEST_URI} !^/cms [NC]
RewriteCond %{REQUEST_URI} !^/vorschau [NC]

RewriteCond %{REQUEST_URI} !^/domain/.*$
RewriteRule ^(.*)$ /subfolder/$1
# end redirect everything to the subfolder

Now i wanted to add this new rule for adding a trailing slash, but then these nested rules does not work together!

So www.domain.de/test should get a trailing slash automatically. Or the other way round: every url WITH trailing slash should redirect to the one without (I don't know which way is better!).

    # Add a trailing slash to URLs that have none
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(.*)/$
    RewriteRule ^(.*)$ http://www.domain.de/$1/ [L,R=301] 

Can anyone help me? :) Thank you!


Solution

  • I've found another way to enforce a no-trailing-slash policy from this stackoverflow-posting: Htaccess: add/remove trailing slash from URL

    And this code works for me:

    # To enforce a no-trailing-slash policy with subfolder
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [R=301,L]