- 无论ip直接访问,还是通过域名访问,最终都是通过ip访问到服务器
- 浏览器访问时会携带Host参数,通过ip访问时携带的是ip,通过域名访问时携带的是域名
- nginx收到请求后判断host的值,如果判断出不是通过域名访问的则拒绝,通过域名访问的则正常放行,最终实现
ningx配置如下
server {
listen 9001;
server_name xxx.xxx.com;
client_max_body_size 2000M;
# 一定要注意空格,没有空格配置失效
if ( $host != 'xxx.xxx.com' ) {
return 403;
}
location / {
root htmlh5;
index index.html index.html;
}
}
允许多个host访问
map $host $is_allowed_host {
default 0;
terminal.hqterminal.com 1;
"114.94.20.15" 1;
}
server {
listen 9001;
server_name xxx.xxx.com;
client_max_body_size 2000M;
# 使用映射变量检查Host是否合法
if ($is_allowed_host = 0) {
return 403; # 如果Host不在允许列表中,则返回403
}
location / {
root htmlh5;
index index.html index.html;
}
}