Run PHP pages without an extension

蹲街弑〆低调 提交于 2021-02-10 07:39:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!