0

How can I force www, remove trailing slash, force non-ssl and remove the .php extension using .htaccess?

I've tried a lot of things but I'm getting 500 internal server error a lot.

Thanks.

Jamesking56
  • 3,683
  • 5
  • 30
  • 61

1 Answers1

1

Force www:

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

Remove trailing slash:

RewriteRule ^(.*)/$ $1 [R=301,L]

Force HTTP:

RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ %{HTTP_HOST}/$1 [R=301,L]

About removing the php extension, i'm not completely sure, but you could try this:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ %{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ %{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^([^/.]+)$ $1.php [L]

However, this may fail for directories. But since i'm no longer using apache, i can just guess and not test it.


So, a combined solution could look like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ %{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ %{HTTP_HOST}/$1 [R=301,L]

RewriteRule ^([^/.]+)$ $1.php [L]
RewriteRule ^(.*)/$ $1 [R=301,L]
SGL
  • 341
  • 2
  • 15
  • That doesn't work. If I go to example.dev/about, it redirects me to www.example.dev/Users/James/Sites/example/about which isn't right at all – Jamesking56 Feb 21 '14 at 21:27
  • That's what i meant. I'll try to check and fix that. – SGL Feb 21 '14 at 23:29