Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .htaccess to remove PHP file extension from URL

I just finished installing a LAMP stack on Ubuntu 12, and have run into an issue with Apache's .htaccess file. I have the rewrite and redirect mods enabled, and the .htaccess file is working (the URI will redirect to 'www' if there is no 'www' present), but no matter what I try, I cannot get it to remove file extensions. I've tried the <Files> directive with no luck. My current file consists of the following:

RewriteEngine On

# Remove file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)$ $1.php [L]

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

Any suggestions on how to fix this very annoying problem?

like image 995
Cora Avatar asked Nov 24 '12 10:11

Cora


People also ask

What is .htaccess file in PHP?

The . htaccess (Hypertext Access) file is an Apache distributed server configuration file. You can use the . htaccess file to set server configurations for a specific directory. This directory can be the root directory of your website or another subdirectory where the .


1 Answers

You don't use htaccess to do this, you use your app to remove the extensions, and htaccess to map extension-less urls to real files. This rule

# Remove file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) $1.php [L]

Says, "if the requested resource doesn't exist as a file, look for the resource with a .php extension". So you remove the extension from all links in your app, and this rule will make the php file run without the extension. Your htaccess is fine as-is, you need to update your app.

like image 187
Ben Lee Avatar answered Oct 21 '22 07:10

Ben Lee