简体   繁体   中英

How can I remove and redirect all .php extensions, redirect “www”, and remove trailing slashes?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM