问题
I want to run my PHP web pages on an apache web server without the .php
extension. So I added the following code:
RewriteEngine on
RewriteBase /
Rewritecond %{REQUEST_URI} !(^/?.*\..*$) [NC]
RewriteRule (.*)$ $1.php [NC]
in the .htaccess
file. This solves my problem but another problem arises. I cannot view the content of any directory (i.e. the file contained in the directory). Please provide me an alternate RewriteRule
without this problem.
回答1:
You need to make sure that the request URI points to an existing resource if you append the.php to the end of it:
RewriteEngine on
RewriteBase /
Rewritecond %{REQUEST_URI} !(^/?.*\..*$) [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)$ $1.php [NC]
the line RewriteCond %{REQUEST_FILENAME}.php -f
checks if a ".php" is appended to the requested URI, it mapes to an existing file (-f
).
回答2:
You can use this code, it is working on my website:
RewriteEngine On
#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
#redirect external .php requests to extensionless url
#RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
#RewriteRule ^(([^/]+/)*[^.]+)\.php $1 [R=301,L]
回答3:
Try setting DirectoryIndex above your RewriteCond
:
DirectoryIndex index.php
来源:https://stackoverflow.com/questions/11624639/run-php-pages-without-an-extension