如何禁止HTTP访问PHP文件



我正在尝试使用mod_rewrite重写url。这是我的。htaccess文件中的重写规则:

RewriteRule ^([a-z]+)/?$ $1.php

如果用户输入example.com/contact,则加载example.com/contact.php文件的内容。

问题是,这给我留下了重复的内容,因为现在example.com/contactexample.com/contact.php都显示相同的信息。

我想禁止访问所有PHP文件,如果用户试图通过HTTP访问,但允许脚本访问(我需要我的应用程序工作)。我如何使用。htaccess做到这一点?

我所尝试的一切都阻止了脚本和HTTP访问。例如,在.htaccess中使用以下命令禁止HTTP访问,但也会导致脚本停止工作:

Deny from all

您可以使用THE_REQUEST

你的代码现在应该是这样的

Options -MultiViews
RewriteEngine On
# if file exists and has ".php" extension then redirect to extensionless equivalent
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{THE_REQUEST} s/([^/]+).php(?:s|?) [NC]
RewriteRule ^ /%1? [R=301,L]
# if uri + ".php" exists then internally rewrite to "uri.php"
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^/]+)$ /$1.php [L]
  • http://example.com/contact.php将重定向到http://example.com/contact
  • http://example.com/contact将内部重写为/contact.php

最新更新