问题
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 error
s. 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!
回答1:
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.
#Redirect users loading /foo/bar.php to /foo/bar/
RewriteRule ^(.*)\.php$ $1/ [R]
#Rewrite /foo/bar/ (what the user sees) silently to /foo/bar.php
RewriteRule ^(.*)/$ $1.php [L]
The [R]
at the end of the first rule specifies to redirect rather than rewrite, so that the user loads /foo/bar/. The $1
at 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 evaluating RewriteRules
.
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 than mydomain.com/foo/bar/
, then add a leading slash before the $1
in 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.
回答2:
Ultimately I got this working using the following code, a combination of my original finding and David Ravetti's help.
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
RewriteRule ^(.*)/$ $1.php [L]
来源:https://stackoverflow.com/questions/14432305/htaccess-rewrite-foo-bar-to-foo-bar-php