.htaccess add trailing slash if no extension before the last trailing slash

Viewed 270

I have a code here which rewrites url by adding trailing slash at the end. Condition:

  1. No File Extension
  2. No slash at the end

RewriteEngine On
RewriteCond %{REQUEST_URI} !\..*$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/Brian/$1$2/ [L,R=301]

If the url is:

http://localhost:8080/Brian/test123 -> http://localhost:8080/Brian/test123/ - CORRECT
http://localhost:8080/Brian/test123. -> http://localhost:8080/Brian/test123. - CORRECT
http://localhost:8080/Brian/test123.awd -> http://localhost:8080/Brian/test123.awd - CORRECT

http://localhost:8080/Brian/test123.awd/a -> http://localhost:8080/Brian/test123.awd/a - THIS IS MY PROBLEM

I want to make the result like this.

http://localhost:8080/Brian/test123.awd/a/

Please help. Thanks!

1 Answers
RewriteCond %{REQUEST_URI} !\..*$

So it would seem you need to only look in the last path segment, rather than anywhere in the URL-path. (Incidentally, the above CondPattern is the same as !\.)

For example:

RewriteCond %{REQUEST_URI} !\.[^/]*$

[^/]* matches any character except slash to the end of the string, so it will only match last path segments that are not followed by a slash.


Aside: It looks like your .htaccess file is located inside the /Brian subdirectory. You could "simplify" this a bit and avoid having to explicitly state the subdirectory in the RewriteRule substitution. For example:

RewriteCond %{REQUEST_URI} !\.[^/]*$
RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]

The RewriteRule pattern !/$ simply checks that the requested URL-path does not already end in a slash (instead of capturing everything when a slash does not occur at the end). The REQUEST_URI server variable contains the full (root-relative, starting with a slash) URL-path, which we have already ascertained does not end in a slash.

Providing you are redirecting to the same scheme + hostname, you don't necessarily need to include this in the substitution string.

Related