I’m looking to set rules in my .htaccess file so that all files with a .php extension can be accessed by replacing the extension with just a slash (/foo/bar/ would silently load /foo/bar.php). Previously, I found this, which is kind of what I’m looking for, except it only changes /foo/bar.php to /foo/bar (notice there is no end slash).
I’m almost a completely newbie when it comes to htaccess, and about 30 minutes of tweaking with the code from the previous link produced nothing by a ton of 500 internal server errors. I’m sure it’s such a simple fix, but neither Google nor trial and error have yet to bring me any results.
Could anyone take a look at the code from the aforementioned post (copied below) and change it so that /foo/bar/ will rewrite to /foo/bar.php?
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]
Many thanks!
Per the comments below, the intent is to have user-visible URLs like /foo/bar/ that actually run php scripts like /foo/bar.php. In addition, you probably want users who try to load /foo/bar.php directly to be redirected to /foo/bar/ for consistency.
The
[R]at the end of the first rule specifies to redirect rather than rewrite, so that the user loads /foo/bar/. The$1at the end of the second rule matches the parentheses (everything prior to the terminating slash) then tacks .php on the end. The[L]means to stop evaluatingRewriteRules.As in my original reply, the use of a leading slash for the replacement string depends on context. With these rules you’ll be able to see the effect of the first rule since it’s a redirect. If the redirect tries to go to
mydomain.comfoo/bar/rather thanmydomain.com/foo/bar/, then add a leading slash before the$1in each rule.Another note – does your php script expect any query strings? There may need to be an additional tweak if it does.
The Apache mod_rewrite reference has more details.