nginx访问控制、用户认证、https
访问控制
可以用在http, server, location, limit_except
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:
拒绝192.168.11.120访问
[root@localhost ~]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
location /test {
deny 192.168.11.120;
echo "aabb";
}
[root@localhost conf]# nginx -s reload
[root@localhost ~]# curl 192.168.11.120/test
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@localhost ~]# curl 192.168.11.120
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>An error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the error log for details.</p>
<p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
禁止除了192.168.11.120之外所有的ip访问
[root@localhost conf]# vim nginx.conf
location /test {
allow 192.168.11.120;
deny all;
echo "aabb";
}
[root@localhost conf]# nginx -s reload
[root@localhost ~]# curl 192.168.11.120/test
aabb
在http上设置禁止192.168.11.120访问
[root@localhost conf]# vim nginx.conf
http {
include mime.types;
default_type application/octet-stream;
deny 192.168.11.120;
[root@localhost conf]# nginx -s reload
[root@localhost ~]# curl 192.168.11.120
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
用户认证
[root@localhost conf]# yum -y install httpd-tools
[root@localhost conf]# htpasswd -c -m /usr/local/nginx/conf/.user_auth huang
New password:
Re-type new password:
Adding password for user huang
[root@localhost conf]# vim nginx.conf
location /test {
auth_basic "test";
auth_basic_user_file ../conf/.user_auth;
echo "test";
}
[root@localhost conf]# nginx -s reload
换到http位置
[root@localhost conf]# vim nginx.conf
http {
auth_basic "test";
auth_basic_user_file .user_auth;
[root@localhost conf]# nginx -s reload
https
6.12 https配置
生成私钥,生成证书签署请求并获得证书,然后在nginx.conf中配置如下内容:
[root@VM-0-17-centos ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.huang.shop huang.shop;
listen 443 ssl;
ssl_certificate 1_huang.shop_bundle.crt;
ssl_certificate_key 2_huang.shop.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
proxy_set_header HOST $host;
}