删除php扩展并允许使用htaccess在没有扩展名的情况下加载文件

时间:2016-11-17 04:40:30

标签: php apache .htaccess mod-rewrite

我试图强行从网址中删除php扩展程序,并允许在没有扩展程序的情况下加载文件。

现在,我正在使用它删除php扩展

RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\ HTTP/
RewriteRule ^(.*)index$ https://www.example.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ https://www.example.com/$1 [L,R=301]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.php\ HTTP/
RewriteRule ^(.+)\.php$ https://www.example.com/$1 [L,R=301]
RewriteRule ^([a-z]+)$ /$1.php [L]

这样可以在没有扩展名的情况下加载文件

Options +Followsymlinks
Rewriteengine On
Rewritebase /
Rewritecond %{Request_Filename} !-f
Rewritecond %{Request_Filename} !-d
Rewritecond %{Request_Filename}.Php -f
Rewriterule ^(.+)$ /$1.Php [L,Qsa]

这样可行,但似乎有点矫枉过正。我正在考虑使用mutiviews来允许在没有扩展名的情况下加载文件,但是由于安全漏洞而决定使用它。

有没有更好的方法来做这两件事?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是PHP中的HTTP路由器。示例将所有请求路由到index.php,否则文件存在。

的.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

的index.php

<?php
switch ($_SERVER['REQUEST_URI']) {
     case '/url1':
          // handle url1
     case '/url2':
          // handle url2
     default:
          // 404 page
}

如果您想更简单一点,请查看SlimLaravel

要覆盖到PHP文件的路由URL可能是这样的。

.htaccess

 Rewrite On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule RewriteRule ^(.+)$ /$1.php [QSA,L]