【问题标题】:Is it possible to apply rewrite first and then Deny/Apply IP block with .htaccess?是否可以先应用重写,然后使用 .htaccess 拒绝/应用 IP 块?
【发布时间】:2013-05-20 10:23:29
【问题描述】:

是否可以在使用 .htaccess 文件拒绝/允许 IP 阻止之前应用重定向?

我尝试关注,但未列入白名单的重定向用户被阻止,因此这意味着拒绝/允许部分被执行,即使他们应该被重定向。重定向部分工作正常,因为我在没有任何 IP 阻塞的情况下对其进行了测试。我希望重写中的 [L] 标志会在到达 IP 阻止部分之前“停止” .htaccess 执行。

RewriteCond %{HTTP_HOST} !^blog\.mysite\.com$ [NC]
RewriteRule (.*) http://www.mysite.com [L,NC,R=301]

Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

为什么我这样做是因为我应该保护对http://www.mysite.com/blog 的访问,同时仍然显示与站点显示的其他无效页面相同的 404。如果先进行 IP 阻止,我将无法显示站点框架生成的相同 404 页面。

是我做错了什么还是不可能这样做?

【问题讨论】:

    标签: .htaccess


    【解决方案1】:

    您可以使用重写条件来检查 IP 地址:

    RewriteEngine On
    RewriteBase /
    
    #always redirect blog.mysite.com to www.mysite.com
    RewriteCond %{HTTP_HOST} ^blog\.mysite\.com$ [NC]
    RewriteRule (.*) http://www.mysite.com [L,NC,R=302]
    
    #don't redirect if the accessDenied.php page is accessed
    RewriteCond %{REQUEST_FILENAME} ^accessDenied\.php$
    RewriteRule (.*) - [L]
    
    #redirect all not whitelisted IPs
    RewriteCond %{REMOTE_ADDR} !^111\.111\.111\.111 [or]
    RewriteCond %{REMOTE_ADDR} !^222\.222\.222\.222
    RewriteRule (.*) accessDenied.php [R=302,L]
    
    #only whitelisted IPs will use this rewrite rule
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) index.php?/$1 [L,R=302]
    

    如果ip匹配,则不会满足第二个重写规则,所以什么都不会发生。但是如果ip不匹配,用户会被重定向到你的404错误页面。

    【讨论】:

    • 谢谢,但这不是我想要达到的。我可能很好地解释了这个问题。我想只允许某些同时访问的 IP 访问该站点,因此必须阻止以拒绝所有其他 IP。在 IP 阻塞之前,应该有 ReWrite 条件以查看是否尝试访问特定的 url,在这种情况下使用重写而不是继续进行 IP 阻塞。如果我正确理解您的解决方案,则没有 IP 阻止来阻止除允许 IP 之外的所有 IP。
    • 我更新了我的答案。现在 blog.mysite.com 应该总是被重定向到 www.mysite.com。如果访问其他 url,则只有列入白名单的 IP 才能看到该页面,所有其他 IP 将被重定向到错误页面。但我目前无法测试代码,所以我不能 100% 确定它是否正常工作
    • 有什么方法可以将以下内容应用于已接受的 IP,很抱歉我没有将这些内容包含在原始问题中,因为现在它已经相关。 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L]
    • @Laowai 我再次更新了我的答案。第三段避免了重定向循环(否则accessDenied.php 将一次又一次地重定向到它自己)。下一段将每次访问从未列入白名单的 IP 重定向到 accessDenied.php。这使您可以根据需要在文档末尾添加尽可能多的新重写规则。仅当用户的 IP 被列入白名单时才会使用它们。
    猜你喜欢
    • 2016-10-18
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2016-10-18
    • 2013-06-20
    相关资源
    最近更新 更多