Hide php extension, force trailing slash is a common question, always a crappy answer. Tell me if I'm right

I do not like to ask this question because it was asked a million times, but the answers never seem to be satisfactory, and most threads seem to be left without an accepted answer.

Here's exactly what I need to do (bad URLs intentionally due to low karma):

http://example.com/file.php redirects to http://example.com/file/

http://example.com/file should also be redirected to http://example.com/file/

http://example.com/asdfsadf and http://examplecom/file/asdfasdf should go to page 404

Here is the htaccess magic that I put together with the posts here and elsewhere. It seems to work (unlike most abandoned threads on a topic where there is always strange behavior).

  RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^([^/]+)/$ $1.php RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$ RewriteRule (.*)$ /$1/ [R=301,L] RewriteCond %{THE_REQUEST} ^[AZ]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/ RewriteRule ^(([^/]+/)*[^.]+)\.php http://example.com/$1 [R=301,L] 

As I said, as far as I can tell, this works great even with subdirectories. Can any of the knowledgeable people tell me if I missed something. Is it possible to improve or reduce?

For what it's worth, I also delete www:

  RewriteCond %{HTTP_HOST} ^www.example.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [R=301,L] 

Everything seems to be fine. It turns on after other parts. Is this the best order?

Thanks to everyone, I hope that we get a good, reliable answer for this, because there are many bad ones.

+6
source share
1 answer

Oh, I have an answer to this! This small rewrite fragment for .htaccess login will remove the extension from any file specified in its URL.

 RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php RewriteBase / RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ http://yourdomain.com/$1/ [L,R=301] 

Just paste it at the bottom of the .htaccess file into the root directory. The file is hidden, so make sure "show hidden files" is enabled in your ftp. ETA: The last 3 lines should add a trailing slash to all the files on your site. Remember to replace youdomain.com correctly.

This will remove the ".php" from all your urls in php files! ^ _ ^ I hope I helped

+2
source

Source: https://habr.com/ru/post/889916/


All Articles