nginx配置小记

nginx配置禁止ip访问时,我是这样配置的,把没匹配上域名的80端口请求都走这里。

     server {
          listen 80 default;
          server_name _;
          default_type text/html;
          add_header Content-Type 'text/html;charset=utf-8';
          return 200 '小朋友,请不要黑我,我谢您全家≧◉◡◉≦';
      }

由于的我小破博客也配置了443端口,所以我需要把80重定向到了443,是这样写的

      server {
          listen       80;
          server_name  xingzhen.wang;
          rewrite ^ https://$http_host$request_uri? permanent;
      }

然后我又在443的server里面进行了if判断,判断域名是不是xingzhen.wang,如果不是,就不让访问。

          if ($host != "xingzhen.wang") {
              rewrite ^ http://$host$request_uri? permanent;
          }

这看起来很完美,不过问题来了,我发现在使用默认的二级域名www.xingzhen.wang 时竟然访问不进来,竟然走到了我的defaut80端口。这时我才发现是我的if判断有问题,我是直接判断的wxz.top,并没有判断www.xingzhen.wang ,所以才造成了这个问题。 第一次我是这么改的

          if ($host != "xingzhen.wang" && $host != "www.xingzhen.wang") {
              rewrite ^ http://$host$request_uri? permanent;  
          }

然后我用下面这个命令检测配置文件的时候,竟然发现报错了

./nginx -t
这是报错代码
nginx: [emerg] invalid condition "$host" in /xxx/xxxx/xx/xx/config.conf:54
nginx: configuration file /xxx/xxxx/xx/xx/nginx.conf test failed

后来问了一下强大的百度,才发现原来nginx里面的if不支持&&和||,这时,正则匹配就上场了。 要注意的是这里必须是双引号,不可以是单引号,具体原因我想应该和golang语言里面的单双引号类似,需要注意一下。

          if ($host !~ "xingzhen.wang") {
              rewrite ^ http://$host$request_uri? permanent;  
          }

后来又发现,在我访问80端口的二级域名www.xingzhen.wang 时,同样走到的default80的server里面,我把

      server {
          listen       80;
          server_name  xingzhen.wang;
          rewrite ^ https://$http_host$request_uri? permanent;
      }
	  改成
	  
	  server {
          listen       80;
 #这里也可以使用通配符*和正则匹配,不过我觉得那样就太灵活了,对于我这个小破博客来说没有意义,所以我直接把两个域名都写上了,两个域名都写上的话,其实就相当于这两个域名都会走到这里面
          server_name  xingzhen.wang www.xingzhen.wang;

          rewrite ^ https://$http_host$request_uri? permanent;
      }

王兴振博客
请先登录后发表评论
  • latest comments
  • 总共0条评论