Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing slash if not a directory with apache

I have the following rewrite rules:

#remove the www.
RewriteCond %{HTTP_HOST} ^www.website.co.uk$ [NC]
RewriteRule ^(.*)$ http://local.website.co.uk/$1 [R=301,L]

#this removes php extention
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L] 

# stops you accessing url with.php
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^.?\ ]+)\.php
RewriteRule ^([^.]+)\.php(/.+)?$ /$1%{PATH_INFO} [R=301]

I want to add in a rule that removes the trailing slash if someone tries to access site with one.

eg

website.co.uk/cheese/ should redirect to /cheese

as you can see I have a rule that redirects ursl with the .php extention, not sure where to begin.

I do have directory in the root folder which I do not wish to remove the trailing url, but I can add a ignore rule for those.

Cheers

like image 676
AJFMEDIA Avatar asked Jan 05 '12 15:01

AJFMEDIA


People also ask

How do I get rid of trailing slash?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

How do I remove the last slash from a URL in Java?

String s = "http://almaden.ibm.com/"; s= s. replaceAll("/",""); and this: String s = "http://almaden.ibm.com/"; length = s.

Should not specify a trailing slash?

The short answer is that the trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent. But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs.

Does trailing slash matter?

Historically, a trailing slash marked a directory and a URL without a trailing slash at the end used to mean that the URL was a file. Today, however, trailing slashes are purely conventional, and Google does not care whether you use them; as long as you're consistent.


1 Answers

Make the change below to your .htaccess file

RewriteEngine on
RewriteBase /

#existing rule
#remove the www.
RewriteCond %{HTTP_HOST} ^www.website.co.uk$ [NC]
RewriteRule ^(.*)$ http://local.website.co.uk/$1 [R=301,L]

#new Rule
#if its not a directory
RewriteCond %{REQUEST_FILENAME} !-d
#and it has a trailing slash then redirect to URL without slash
RewriteRule ^(.+)/$ /$1 [L,R=301]

# rest of your existing rules go here
like image 83
Ulrich Palha Avatar answered Oct 02 '22 23:10

Ulrich Palha