Forum Moderators: phranque

Message Too Old, No Replies

Removing trailing slashes in .htaccess

         

Saudiqua

8:21 am on Sep 1, 2011 (gmt 0)

10+ Year Member



Hi Guys

Me again, with my beloved .htaccess file. :)

Basically I need to ensure that all the URLs on my domain do not end in a trailing slash in order to resolve a duplicate content issue ( Google sees trailing slash versions of a URL as a completely different URL).

This is the code I want to use:

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


This is my current htaccess code:

RewriteEngine On

RewriteRule \.asp - [G,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA]



I would like to know if the code I want to use is correct and if so, what would be the best way to include it within my current .htaccess code?

Thanks

S

lucy24

9:48 am on Sep 1, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Your current code looks fine: send all non-valid names to index.php, with the requested name shoved over to the query string. Presumably your php will deal with it.

The first chunk has problems, even aside from two syntax errors which you can find for yourself:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$

Most of the time, {REQUEST_FILENAME} and {REQUEST_URI} are the same thing. So you're looking for a valid filename (-f with no !) that contains "xphp" (php preceded by anything) and that doesn't end in a slash, and then you plan to add ".php" to the end. Looks like an infinite loop to me.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1

I think I'm reading this upside-down. It seems to say that any request for anything that isn't an existing directory but that does end in a slash should be redirected to an address without trailing slash. Except that it won't stop there. Your server will have to reappend the slash to make it into a real directory name, so you're right back where you started. If you want the slash to remain invisible, you will need to rewrite it back in.

For some reason there has been a whole flurry of recent questions involving redirecting from A to B and then rewriting back to A again. Skim the last week or so in this Forum.

Saudiqua

10:02 am on Sep 1, 2011 (gmt 0)

10+ Year Member



Thanks for the reply Lucy, you're very helpful as always..I'll have a relook at the code and get back to you.