5

nginx只允许域名访问,禁止ip访问

 3 years ago
source link: https://www.cnblogs.com/tuyile006/p/15800440.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

nginx只允许域名访问,禁止ip访问

背景:
为什么要禁止ip访问页面呢?
这样做是为了避免其他人把未备案的域名解析到自己的服务器IP,而导致服务器被断网,我们可以通过禁止使用ip访问的方法,防止此类事情的发生。

解决方法:
这里介绍修改配置文件nginx.conf两种方法:
1)在server段里插入如下正则:
listen       80;
server_name  www.yuyangblog.net;
if ($host != 'www.yuyangblog.net'){
   return 403;
}


2)添加一个server
新加的server(注意是新增,并不是在原有的server基础上修改)
server {
  listen 80 default;
  server_name _;
  return 403;
}
原来server里面插入:
listen       80;

server_name  www.yuyangblog.net;

设置成功后,就只能用域名访问网站,不能用ip访问了。

实例配置:

[root@weifeng conf.d]# cat weifeng.conf

server {
listen 80 default;
server_name _;
return 403;
}

server {
        server_name 80 default;
        server_name _;
        rewrite ^(.*) http://www.demo.com;
        }
 
server {
 
        server_name localhost www.demo.com;
 
        root /usr/share/nginx/www;
        index index.html index.htm;
 
        location / {
                index index.php;
                try_files $uri $uri/ /index.html;
        }
 
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
 
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
 
}

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK