重写文件扩展名但拒绝直接访问文件

时间:2011-10-01 23:56:16

标签: php security rewrite hide

我正在寻找一种通过.htaccess隐藏文件扩展名并拒绝直接访问的方法。让我们考虑以下几点:

http://www.xyz.zyx/index.php 

转换为

http://www.xyz.zyx/index OR http://www.xyz.zyx/

直到现在都很好。我想要做的是在用户尝试直接访问时阻止或重定向。例如,如果用户在URL栏中键入以下(扩展名),阻止或重定向:

http://www.xyz.zyx/index.php

我从其他问题中检查了其他答案,但似乎并非如此。

提前感谢帮助像我这样的新手。

1 个答案:

答案 0 :(得分:5)

虽然有人可能质疑这种事情的用处,但它是可行的,所以这里是如何使用.htaccessmod_rewrite中进行的:

RewriteEngine On

# Sets your index script
RewriteRule ^$ index.php [L]

# Condition prevents redirect loops (when script is not found)
RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteCond %{REQUEST_FILENAME} !-f

# Stop here if the file is not found after a redirect
RewriteRule ^(.*)$ notfound.php [L]

# Condition prevents redirect loops (when script is found)
RewriteCond %{ENV:REDIRECT_STATUS} ^$

# Forbid access directly to PHP files
RewriteRule ^.*?\.php$ forbidden [F,L]

# Make sure the filename does not actually exist (images, etc.)
RewriteCond %{REQUEST_FILENAME} !-f

# Append the .php extension to the URI
RewriteRule ^(.*)$ $1.php [L]