htaccess - 如何拒绝访问从主机名和给定文件调用的资源以外的所有资源
htaccess - how deny access to all resource expect for that resource called from hostname and gived file
我有这个 .htaccess:
# Rewrite URL
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond "%{HTTP_HOST}" "!^www.mydomain.com" [NC]
RewriteCond "%{REQUEST_URI}" "!^/myfile.html" [NC]
RewriteRule \.*$ - [F,NC]
</IfModule>
我想要 DENY 访问 ALL 资源,EXCEPT 用于:
- 来自
HTTP_HOST
的所有资源(即 www.mydomain.com);
- 特定给定文件(es.myfile.html)。
以上代码无效。我能解决吗?
谢谢
PS:换句话说,我想做这样的事情:
<?php
if (
$_SERVER["REMOTE_ADDR"] !== "www.mydomain.com" ||
$_SERVER["REQUEST_URI"] !== "/myfile.html"
) {
// redirect 403
}
}
?>
根据您的评论,我认为您需要检查引荐来源网址。你可以试试这条规则:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
RewriteCond %{REQUEST_URI} !/myfile\.html$ [NC]
RewriteRule \. - [F]
请记住,基于 HTTP_REFERER
的阻止不是非常强大的保护,因为客户端可以欺骗此 header。
正在测试 curl
命令:
curl --referer 'http://example.com/' -IL 'http://yourdomain.com/'
HTTP/1.1 403 Forbidden
Date: Thu, 08 Apr 2021 09:28:17 GMT
Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
Strict-Transport-Security: max-age=31536000
Content-Type: text/html; charset=iso-8859-1
curl --referer 'http://yourdomain.com/' -IL 'http://yourdomain.com/'
HTTP/1.1 200 OK
Date: Thu, 08 Apr 2021 09:27:47 GMT
Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
Strict-Transport-Security: max-age=31536000
X-Powered-By: PHP/8.0.3
Content-Type: text/html; charset=UTF-8
参考文献:
我有这个 .htaccess:
# Rewrite URL
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond "%{HTTP_HOST}" "!^www.mydomain.com" [NC]
RewriteCond "%{REQUEST_URI}" "!^/myfile.html" [NC]
RewriteRule \.*$ - [F,NC]
</IfModule>
我想要 DENY 访问 ALL 资源,EXCEPT 用于:
- 来自
HTTP_HOST
的所有资源(即 www.mydomain.com); - 特定给定文件(es.myfile.html)。
以上代码无效。我能解决吗? 谢谢
PS:换句话说,我想做这样的事情:
<?php
if (
$_SERVER["REMOTE_ADDR"] !== "www.mydomain.com" ||
$_SERVER["REQUEST_URI"] !== "/myfile.html"
) {
// redirect 403
}
}
?>
根据您的评论,我认为您需要检查引荐来源网址。你可以试试这条规则:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
RewriteCond %{REQUEST_URI} !/myfile\.html$ [NC]
RewriteRule \. - [F]
请记住,基于 HTTP_REFERER
的阻止不是非常强大的保护,因为客户端可以欺骗此 header。
正在测试 curl
命令:
curl --referer 'http://example.com/' -IL 'http://yourdomain.com/'
HTTP/1.1 403 Forbidden
Date: Thu, 08 Apr 2021 09:28:17 GMT
Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
Strict-Transport-Security: max-age=31536000
Content-Type: text/html; charset=iso-8859-1
curl --referer 'http://yourdomain.com/' -IL 'http://yourdomain.com/'
HTTP/1.1 200 OK
Date: Thu, 08 Apr 2021 09:27:47 GMT
Server: Apache/2.4.46 (Unix) OpenSSL/1.1.1j PHP/8.0.3
Strict-Transport-Security: max-age=31536000
X-Powered-By: PHP/8.0.3
Content-Type: text/html; charset=UTF-8
参考文献: