user198003
user198003

Reputation: 11151

RewriteRule of .htaccess, with slash at the end

I have two kinds of links on my site: first are finishing with .html, and second that are finishing with / (with slash, in a case that filename is not finishing with .html).

Cause of some rewriting rules, in a case that file is not .html, and if is added / at the end, URL is not properly rewritten.

Like:

It is ok with link: http://mysite.com/cars/fast-cars

But not ok with link: http://mysite.com/cars/fast-cars/

So, what I need is when URL is finishing with / and not with (.html/), to be redirected to same page, without /, or in this case:

http://mysite.com/cars/fast-cars/ to be redirected to http://mysite.com/cars/fast-cars.

Hope I was clear, and that you can help me with that htaccess rule. Thank you in advance.

UPDATED: i did found part of solution here: .htaccess with or without slash.

but, also, my rule should not be valid for some subdirectories (like directory admin, orders, etc). can it be defined also with same rule?

UPDATE 2: I have rules like:

RewriteRule ^cars/fast-cars$ /seopage.php?marker=fast-cars$1

Also, tryed with rule that works:

RewriteRule (.*)/$ $1 [L,R=301]

But that rule have to be bypassed for some directories (ie. admin, orders, etc.).

Upvotes: 2

Views: 2730

Answers (1)

LazyOne
LazyOne

Reputation: 165118

You can do this in few ways (choose the one that works best for you).

1) Remove trailing slash / for non-existing files and folders:

# remove trailing slash for non-existing files and folders
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [L,R=301]

2) Remove trailing slash / with exceptions

# remove trailing slash except some folders
RewriteCond %{REQUEST_URI} !^/(admin|orders)
RewriteRule ^(.*)/$ $1 [L,R=301]

3) You can even combine it together (which can be too much):

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

Also, consider adding this directive somewhere at the top -- documentation:

DirectorySlash Off

Upvotes: 5

Related Questions