.htaccess黑名单来自文本文件和重定向

时间:2017-07-05 20:44:14

标签: regex apache .htaccess mod-rewrite blacklist

我有一个网站,我希望仅在出现在黑名单文件中时才重定向收到的请求。我想将文件存储在公共html目录之外,所以它就像var/www/blacklists/example.com.blacklist,内容看起来像

hello
about
contact
portfolio

如果我的网站为example.com且用户访问https://example.com/goodbye,只要黑名单中的“再见”不是,它就会重定向到{{1} }。

如果用户在黑名单中访问https://somethingelse.com/goodbye并且“你好” ,则会正常解决。

此外,所有解析通常需要强制ssl的请求。 https://example.com/helloexample.com/hello应改写为http://example.com/hello

谢谢, 豪伊

1 个答案:

答案 0 :(得分:0)

  1. DocumentRoot之外的任何路径中创建文本文件。每行应包含由单个空格分隔的2列。第一列应具有列入黑名单的路径值,第二列应具有值1。示例如下:

    cat /tmp/blacklist.txt
    
    hello 1
    about 1
    contact 1
    portfolio 1
    
  2. 然后在httpd.conf内插入一条新的RewriteMap行:

    # First, we configure the "default" to be a very restrictive set of
    # features.
    <Directory />
         # Existing directives here
         # followed by this RewriteMap
         RewriteMap blacklist "txt:/tmp/blacklist.txt"
    </Directory>
    
  3. 重启apache服务器

  4. 最后,在您的网站根目录.htaccess中有以下规则:

    RewriteEngine On
    
    RewriteCond ${blacklist:$0} !=1
    RewriteRule .+ https://somethingelse.com%{REQUEST_URI} [L,NE,R=302]
    
    RewriteCond %{HTTPS} off
    RewriteCond ${blacklist:$0} =1
    RewriteRule .+ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]