varnie
varnie

Reputation: 2595

mod_rewrite: remove trailing slash for specific files only

I am trying to remove the trailing slash from the urls ending with some file extension only, .txt.

Here is the full .htaccess file:

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} (.*)\.txt.html
RewriteRule ^(.)\.txt.html /$1.txt [R=301,L]

RewriteCond %{THE_REQUEST} (.)\.txt
RewriteRule ^(.)\.txt $1.txt.html [L]

RewriteCond %{THE_REQUEST} (.)\.txt/
RewriteRule ^(.*)\.txt\/ $1.txt [R=301]

Everything is fine except that the rule for for .txt/ adds a full path to the url. Is it possible to make it work with relative paths?

For example, this url

http://test.local:8080/doc/Cons/Bo/Dwnlds/Test.txt/

goes to this

http://test.local:8080/Users/dev1/Documents/96/test.org/doc/Cons/Bo/Dwnlds/Test.txt.

How do I fix this issue?

Upvotes: 0

Views: 156

Answers (1)

Capsule
Capsule

Reputation: 6159

You need to add a leading slash to your target as (.*) will not contain it, hence the weird file system path as a result:

RewriteRule ^(.*)\.txt\/ /$1.txt [R=301]

It actually happens because the RewriteRules defaults to a filesystem path if it exists (in your case, it's hard to tell if your target is an URL-path or a filesystem path because there's no base folder). See the documentation on these at http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule

Upvotes: 1

Related Questions