apache 基于ip的mod_rewrite
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1073852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mod_rewrite based on ip
提问by Josh
I'd like to implement mod_rewrite to put my site into maintenance. Basically all IP addresses except a handful we specify would be forwarded to a static html page.
我想实施 mod_rewrite 来维护我的网站。基本上除了我们指定的少数 IP 地址之外的所有 IP 地址都将被转发到静态 html 页面。
Please can someone help with this rule. Also is there a way to turn this on and off easily without editing the htaccess file?
请有人帮忙处理这条规则。还有一种方法可以在不编辑 htaccess 文件的情况下轻松打开和关闭它吗?
回答by Vinko Vrsalovic
You can use the REMOTE_ADDRvariable in a RewriteCond
您可以在 RewriteCond 中使用REMOTE_ADDR变量
RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteRule ^ /maintenance.html
Just change the condition to match the IPs you want, for more than one you can use ^(ip1|ip2|...|ipn)$.
只需更改条件以匹配您想要的 IP,对于多个 IP,您可以使用 ^(ip1|ip2|...|ipn)$。
About how to disable the maintenance mode without changing the .htaccess file I think that's not possible short of writing a program that would delete it or otherwise modify it, an easy one would be to rename it.
关于如何在不更改 .htaccess 文件的情况下禁用维护模式我认为不可能编写一个程序来删除它或以其他方式修改它,一个简单的方法是重命名它。
回答by Alexander Mikhailov
I'd like to slightly correct Vinko Vrsalovic's answer.
我想稍微纠正 Vinko Vrsalovic 的回答。
RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteRule ^ /maintenance.html
This rule result will be infinite loop and HTTP server error, because it will be executed on redirection page too. To make it work you should exclude redirection page from the rule. It can be done this way:
这个规则的结果将是无限循环和HTTP服务器错误,因为它也会在重定向页面上执行。为了使其工作,您应该从规则中排除重定向页面。可以这样做:
RewriteCond %{REMOTE_ADDR} !^10\.0\.1\.1$
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteRule .* /maintenance.html [R=302,L]
回答by 8ctopus
Small improvement to Alexander's answer, it's not necessary to use regular expression for the IP address.
亚历山大的回答的小改进,没有必要对 IP 地址使用正则表达式。
RewriteCond %{REMOTE_ADDR} !10.0.0.1
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteRule .* /maintenance.html [R=302,L]
回答by dusoft
you could enable this state and disable it via some admin interface that is able to write to .htaccess (e.g. permissions set to 755 or 777). it would just always find the .htaccess, insert those two lines at the beginning and on disabling maintenance it would delete those two lines, leaving the rest of the file untouched
您可以通过一些能够写入 .htaccess 的管理界面启用并禁用它(例如权限设置为 755 或 777)。它总是会找到 .htaccess,在开头插入这两行,在禁用维护时,它会删除这两行,使文件的其余部分保持不变

