atazmak
atazmak

Reputation: 49

Remove ? and / at the end of urls

I noticed that my urls are duplicated (or better to say triplicated). I've 3 versions of the same page, something like:

www.example.com/cars/mercedes

www.example.com/cars/mercedes?

www.example.com/cars/mercedes/

I'ld like redirect [301] the urls ending with ? and / to the clean version.

I've already set a canonical tags to www.example.com/cars/mercedes but anyway the pages are still reachable from the other two versions and I don't like this.

I tried something like:

RewriteEngine On
RewriteCond %{THE_REQUEST} ? HTTP [NC]
RewriteCond %{THE_REQUEST} / HTTP [NC]
RewriteRule .? http(s)?://www.%{HTTP_HOST}%{REQUEST_URI}? [R=301,L]

but it doesn't work. Any idea?

Upvotes: 2

Views: 48

Answers (1)

anubhava
anubhava

Reputation: 785008

You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s/([^?]*)[?/]\s
RewriteRule ^ /%1? [NE,R=301,L]

This will remove trailing / or ? from your URL.

Make sure to test it after clearing your browser cache.

Upvotes: 1

Related Questions