从网址中删除php文件扩展名

时间:2014-02-15 20:52:53

标签: php apache .htaccess mod-rewrite

我知道这个问题已被问过1000次,我可能也尝试了1000个建议,但仍然没有。

我想删除php文件扩展名并用斜杠替换它(斜杠不是那么重要但是要删除扩展名)。

我的项目位于: 本地主机/〜FN / MyProject的/

它包含两个文件夹,public和includes。所以所有公共文件都在公共文件夹中:localhost / ~fn / MyProject / public / index.php

我已经尝试了很多建议,但大多数建议根本不起作用。我收到内部服务器错误,禁止或404.我将.htaccess放入公用文件夹。 Mod重写已打开。 stackoverflow上没有任何成功,也没有外部资源(例如http://alexcican.com/post/how-to-remove-php-html-htm-extensions-with-htaccess/)。例如,使用来自相关网页的重写规则显示403 Forbidden甚至可以访问索引。 我可能做错了什么提示?我真的被卡住了。非常感谢!

5 个答案:

答案 0 :(得分:2)

如果您的htaccess位于公共项目文件夹中,请尝试使用此代码

Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{THE_REQUEST} ^.*public/(.+)\.php
RewriteRule ^(.*)$ /~fn/MyProject/public/%1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ /~fn/MyProject/public/$1.php [L]

答案 1 :(得分:0)

如果目录中包含Index.php,则当您浏览到该文件夹​​时,该URL将不会显示文件名。 example.com/index.php只会显示为example.com。您可以使用PHP包含将每个页面拉入索引页面以隐藏文件名,但这不是最佳做法。

答案 2 :(得分:0)

将它放在localhost / ~fn / MyProject /中的.htaccess文件中(所以文件将是localhost / ~fn / MyProject / .htaccess):

RewriteRule ^(.+?)\.php$ $1/ [QSA,L]

这会捕获以.php结尾的任何内容,删除.php,添加/,并根据需要附加任何查询字符串。

答案 3 :(得分:0)

如果你只想从index.php删除扩展名“.php”,你应该使用mode_rewrite

 RewriteRule ^index.php$ index // or
 RewriteRule ^index.php$ /

但最好的方法是实现机制来重写所有URL并在前端脚本中管理(index.php);

如果你想使用mode_Rewrite,你可以检查你的Apache服务器上是否启用了mod_Rewrite。转到apache.conf并检查是否行

 LoadModule rewrite_module modules/mod_rewrite.so

未启用,不要忘记重启apache!

你可以在apache.conf中重写规则类型

 <IfModule mod_rewrite>
     RewriteEngine On
 </IfModule>

或包含类似于.htacces

的内容
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME}  !-l
  RewriteCond %{REQUEST_FILENAME}  !-d
  RewriteCond %{REQUEST_FILENAME}  !-f
  RewriteRule .* index.php?%{QUERY_STRING} [L]

现在,来自网址的所有迹象都会转到你曾经的index.php。在这里你可以做到这一切你需要做什么,例如你可以调用一些控制器。

如果你得到403 Forbiden别忘了检查文件的chmod。

答案 4 :(得分:0)

要从PHP文件中删除.php扩展名,例如yoursite.com/demo.php到yoursite.com/demo,您可以将以下代码添加到.htaccess文件中:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
相关问题