Forum Moderators: phranque

Message Too Old, No Replies

htaccess rewrite and redirect

htaccess rewrite and redirect

         

alexrose

1:22 pm on Sep 2, 2010 (gmt 0)

10+ Year Member



Hello,

I have a little problem with a htaccess file; here is what I'm trying to do:

1) if_page_accessed( www.site.tld/page.php ) => redirect( www.site.tld/page/ )

2) if_page_accessed( www.site.tld/new-page.php?id=2 ) => redirect( www.site.tld/new-page/2/ )

with automatic redirect, to avoid duplicate content on google.
Here is what I made so far,
- add www. to site.tld
- remove .php extension
- add a trailing slash
- automatic redirect for 1)

This is my .htaccess file
## start engine
Options +FollowSymLinks
RewriteEngine on

## non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

## remove extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/$ $1.php

# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

# do the magic
RewriteCond %{THE_REQUEST} ^[A-Z]+\ (/[^\ ]*)\.php[?\ ]
RewriteRule \.php$ %1/ [R=301,L]


## testing area
#RewriteRule ^new-page/(.*)/$ new-page.php?id=$1


Do you have any ideea?

Thanks,
Alex

jdMorgan

2:59 pm on Sep 2, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A quick overview... Bit of a hurry this morning, so please pardon the abruptness...

All of your redirects (rules with [R=301] flags) need the protocol and domain name specified in the RewriteRule substitution field to avoid hostname canonicalization problems.

Your rules are not in the correct order, and the performance of your rules with "-f" and "-d" checking can be much improved by re-ordering the RewriteConds to put these checks last.

Also, your comments are vague - some to the point of being incorrect.

See Proper Order for htaccess directives [webmasterworld.com] and Reducing Costly Rewrites in Wordpress [webmasterworld.com] in our Apache Forum Library. Both of these threads contain information that I believe you will find quite useful.

Please post questions back here. :)

Jim

alexrose

3:54 pm on Sep 2, 2010 (gmt 0)

10+ Year Member



Hi,

Thanks for your reply. As you can see, this is something relative new for me. Can you be more explicit, please? :)

ps: i didn't use the domain name in rewrite rule because i want to use this script on more domains.

Thanks,
Alex