.htaccess RewriteRule的多个条件

时间:2017-11-06 16:59:44

标签: apache .htaccess mod-rewrite url-rewriting

我真正想做的事情:

  • 域example.com必须只能从5个指定的IP(白名单)
  • 访问
  • url example.com/example/test必须可从所有IP
  • 访问

尝试写入.htaccess规则:

const a = {};
a.name = "";
console.log(a.name);

伪代码中的条件看起来像

RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^1.1.1.1 [OR]
RewriteCond %{REMOTE_ADDR} !^2.2.2.2 [OR]
RewriteCond %{REMOTE_ADDR} !^3.3.3.3 [OR]
RewriteCond %{REMOTE_ADDR} !^4.4.4.4 [OR]
RewriteCond %{REMOTE_ADDR} !^127.0.0.1 
RewriteCond %{REQUEST_URI} !^/example/test$
RewriteRule ^(.*)$ app.php [R=403,L]

IF REMOTE_ADDR IS NOT (1.1.1.1 OR 2.2.2.2 OR 3.3.3.3 OR 4.4.4.4 OR 127.0.0.1) AND REQUEST_URI IS NOT /example/test THEN ACCESS DENIED 文件有效,条件看起来像逻辑,哪里可能有问题,因为在每个请求中我得到.htaccess响应

(IP地址不真实,出于安全原因我改为假)

2 个答案:

答案 0 :(得分:2)

RewriteEngine On

# Allow /example/test 
RewriteCond %{REQUEST_URI} ^/example/test$ 
RewriteRule ^ - [L]

# Allow access to rest of the site to  5 IPs 
RewriteCond "%{REMOTE_ADDR}" "!=1\.0\.0\.1"     
# Example IP6 address
RewriteCond "%{REMOTE_ADDR}" "!=::2" 
RewriteCond "%{REMOTE_ADDR}" "!=3\.3\.3\.3" 
RewriteCond "%{REMOTE_ADDR}" "!=4\.4\.4\.4"
RewriteCond "%{REMOTE_ADDR}" "!=5\.5\.5\.5"
RewriteRule ^ - [R=403,L]

# Arrive to app.php
RewriteRule .? app.php [L]

答案 1 :(得分:1)

使用:

RewriteEngine On
RewriteRule ^example/test$ - [L]

RewriteCond %{REMOTE_ADDR} !^1\.1\.1\.1
RewriteCond %{REMOTE_ADDR} !^2\.2\.2\.2
RewriteCond %{REMOTE_ADDR} !^3\.3\.3\.3
RewriteCond %{REMOTE_ADDR} !^4\.4\.4\.4
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1 
RewriteRule ^ - [F,L]

RewriteRule ^ app.php [L]