1

I've been trying to remove ".php" from all of the pages on my website, whilst also removing all trailing slashes and "www" from URLs using .htaccess. I have been able to use one or two of these at the same time, but not all. I would really appreciate any help.

For example:

  • example.com/ to example.com
  • www.example.com to example.com
  • example.com/index to example.com
  • example.com/index.php to example.com
  • example.com/chatroom.php to example.com/chatroom
  • example.com/directory/ to example.com/directory

I would like to ensure that the old URLs redirects to the new ones, and I don't have any directories that share names with PHP files. In my .htaccess file I also have code blocking particular referrers and specifying 403 and 404 errors. Thank you very much!

Deshar
  • 21
  • 2

2 Answers2

0

I just had the same question today regarding the trailing slashes. This is how I ended up solving it in my .htaccess file (important are DirectorySlash and the first rewrite rule):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Do not automatically add a slash for existing directories
DirectorySlash Off


#No trailing slash. This means that an URL entered with trailing / will change to an URL without trailing /
#The !-d rule can be included so that any URLs to existing directories are not changed
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

#Allow URL's which do not have the php file extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^  %{REQUEST_FILENAME}.php [L]


#Redirect any file which does not exist to the index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php [R=301,L]

</IfModule>

So if you type as URL example.com/index/ it would redirect to example.com/index. If you type example.com/chatroom (and an chatroom.php exists) it still has example.com/chatroom in the URL but your PHP script receives example.com/chatroom.php

What you would have to add are the two cases to redirect index.php to / and to remove the www

What I have included (and I don't know if you need it) is the last rule which redirects any non existing files to index.php

Tho
  • 16
  • 1
0

Hide PHP using htaccess URL rewriting

URL Rewriting for beginners

How to do URL re-writing in PHP?

URL Rewriting tool

Check above urls. In these tutorials you can see how to rewrite URLs.

Community
  • 1
  • 1
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
  • Thank you for the links, but I'm still very confused as to how to do the redirects. They don't really show how to do all this at the same time. – Deshar Nov 22 '11 at 07:02
  • For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement. Options +FollowSymlinks RewriteEngine on RewriteRule ^(.*)\.htm$ $1.php [nc] Have you checked these lines. You can download the .htaccess file from any site. – Code Lღver Nov 22 '11 at 07:56