1

I've inherited a web application, and in it is the following set of .htaccess rules. It appears to me that they do nothing. Can someone explain what they're doing?

To me, it looks like they're matching only hits to the site root, checking if the directory doesn't exist (!), and then 301 redirecting to the site root.

RewriteCond %{REQUEST_URI} /$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ $1 [L,R=301]
e_i_pi
  • 223
  • 1
  • 2
  • 10

2 Answers2

2

It removes the slash at the end of any URL

e.g.:

https://example.com/welcome/

becomes:

https://example.com/welcome

The second RewriteCond specifies that the rule only matches when the URL does not match an existing directory on the disk, (it could be a file for example) of course, automatically.

OverCoder
  • 143
  • 1
  • 8
2

Just to add to OverCoder's answer... as already stated, this code removes the slash at the end of the URL (except for directories) ...

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

However, the first RewriteCond directive here is indeed superfluous and can be removed. This simply checks that the URL ends in a slash, which is what the RewriteRule pattern (ie. ^(.+)/$) has already established.

And the second RewriteCond directive makes sure we are not requesting a directory. A directory requires a trailing slash. By default, mod_dir will append a trailing slash if you request a directory without. So, if you then removed the trailing slash on directories with mod_rewrite then you'd likely create a redirect loop.

MrWhite
  • 12,647
  • 4
  • 29
  • 41