我目前正在使用mod_rewrite进行内部重定向
RewriteCond %{REQUEST_URI} ^/pattern$
RewriteRUle .* file.php
但是,我希望通过将对该文件的请求重定向到未找到网页的网址来阻止对file.php
的直接访问。
RewriteCond %{REQUEST_URI} /file.php
RewriteRule .* page-not-found.php
问题是第二条规则在第一次重定向时也适用,因此会破坏我的第一次内部重定向。
[问]有没有办法允许第一次重定向,但阻止直接访问重定向文件?
答案 0 :(得分:7)
使用ENV:REDIRECT_STATUS
变量(请参阅mromaine的contribution至"Hidden features of mod_rewrite" community wiki:
RewriteCond %{REQUEST_URI} ^/pattern$
RewriteRule .* file.php
# Redirect direct access to file.php
RewriteCond %{REQUEST_URI} /file.php
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule .* page-not-found.php
测试用例:
somefile.htm
somedir
的索引文件file.php
文件page-not-found.php
文件每个HTTP响应都是HTTP 200。
答案 1 :(得分:6)
编辑受@ AndrewR的答案启发(但目前的形式似乎对我不起作用 - 看起来第二条规则无论如何都应用了。)a .htaccess only solution使用密钥。
如果遇到有效模式,请在查询字符串中添加密钥。
然后在决定页面重定向时测试该密钥。
RewriteEngine on
Options +FollowSymlinks
RewriteCond %{REQUEST_URI} ^/pattern$
RewriteRule .* /file.php?SUPER_SEKRIT_KEY [QSA]
RewriteCond %{QUERY_STRING} !SUPER_SEKRIT_KEY
RewriteCond %{REQUEST_URI} /file.php
RewriteRule .* /test/page-not-found.php [L,F]
当然使用更复杂的密钥,仅用于内部重定向!否则,用户将能够获取密钥。
答案 2 :(得分:2)
您可以在重写规则的末尾添加[L],表示Last或不再处理。这只适用于Apache配置。它在.htaccess文件中不起作用。
RewriteEngine On
RewriteCond %{REQUEST_URI} pattern$
RewriteRule .* /file.php [L]
RewriteCond %{REQUEST_URI} file.php$
RewriteRule .* /page-not-found.php [L]
答案 3 :(得分:2)
仅使用.htaccess执行此操作的更简单方法。
将file.php移动到名为securedir的新目录中。在根目录中使用此.htaccess文件。
RewriteEngine On
RewriteRule ^pattern$ securedir/file.php
在那里的.htaccess文件中阻止访问secureir中的任何内容。 (或者,如果您愿意,可以将它们引回到不同的页面。)
deny from all