Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide php extension, force trailing slash - common question, always a crappy answer. Tell me if I got it right

I hate to ask this question because it's been asked a million times, but the answers never seem satisfactory, and most of the threads seem abandoned without an accepted answer.

Here's exactly what I need to do (bad urls are intentional due to low karma):

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

http://example.com/file must also redirect to http://example.com/file/

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

Here's the htaccess magic I cobbled together from posts here and elsewhere. It seems to work (unlike most of the abandoned threads on the topic, where there's always some 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} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/ 
 RewriteRule ^(([^/]+/)*[^.]+)\.php http://example.com/$1 [R=301,L]

Like I said, as far as I can tell, this works fine, even with subdirectories. Can any more knowledgeable folks tell me if I'm missing something. Could it be improved or shortened?

For what it's worth, I'm also removing the www:

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

It seems to work fine. It is included after the other parts. Is this the best order?

Thanks everyone, I hope we can get a good, reliable answer for this out there because there's a lot of bad ones.

like image 218
freshyill Avatar asked Jun 07 '11 01:06

freshyill


1 Answers

Oh, I have the answer to this one! This little rewrite snippet to go in .htaccess will remove the extension from any file you specify 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 your .htaccess file in your root directory. The file is hidden so make sure 'show hidden files' is enabled in your ftp. ETA: last 3 lines should add a trailing slash to all files at yourcomain.com Do't forget to replace youdomain.com correctly.

That will remove the '.php' from all your urls to php files! ^_^ Hope I helped

like image 85
alt Avatar answered Oct 18 '22 04:10

alt