Search code examples
.htaccesshttp-redirectmod-rewritehttp-status-code-404trailing-slash

htaccess no-trailing-slash policy: non existing urls (404) should not redirect


If I open a non existing url on my site like www.domain.de/abcde/ (with trailing slash) the url redirects to www.domain.de/abcde (without trailing slash) and opens the 404 site after.

But the 404 site should come directly when the url does not exist (without redirecting for the non-trailing-slash policy).

What do I need to add to my htaccess? Thank you!

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

------

starkeens suggestion does only work on a clean htaccess, but I got some more code. It does not work together with the other lines. All the code:

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

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

Any new suggestions? :)


Solution

  • Finally i got a solution that seems to work.. maybe anyone got the same issue and needs the code. Comments for optimization are welcome!

    # trailing Slashes
    
    # to enforce a no-trailing-slash policy with subfolder
    # is the request for a non-existent file?
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # if so, skip the next RewriteRule
    RewriteRule .? - [S=1]
    
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_URI} (.+)/$
      RewriteRule ^ %1 [R=301,L]
    

    Now only existing files get the redirect of my no-trailing-slash policy. Non existing files aren't redirected and occur a 404 page directly, as wished.