访问控制、用户认证、https
访问控制、用户认证、https
一、访问控制
用于location段
allow # 设定允许哪台或哪些主机访问,多个参数间用空格隔开deny # 设定禁止哪台或哪些主机访问,多个参数间空格隔开
# 仅允许192.168.100.20访问server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {echo "Hellow World";allow 192.168.100.20;deny all;}
# 192.168.100.20主机访问curl 192.168.100.10Hellow World# 本机cmd访问(192.168.100.1)curl 192.168.100.10<html><head><title>403 Forbidden</title></head><body><center><h1>403 Forbidden</h1></center><hr><center>nginx/1.24.0</center></body></html>
stub-status模块
stub_status模块主要作用于查看nginx的一些状态信息
server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location /status {echo "Hellow World";stub_status on;}
curl 192.168.100.10/statusActive connections: 1server accepts handled requests4 4 4Reading: 0 Writing: 1 Waiting: 0
Active connections: # 当前nginx正在处理的活动连接数server accepts handled requests4 4 4 # nginx总共处理了4个连接,成功创建4次握手,总共处理了4个请求Reading: # nginx读取到客户端的Header信息数Writing: # nginx返回给客户端的Header信息数Waiting: # 开启keep-alive的情况下,这个值等于active-(reading+writing),意思就是nginx已经处理完成,正在等候下一次请求指令的驻留连接。所以,在访问效率高、请求很快就被处理完毕的情况下,waiting数比较多是正常的。如果reading+writing数较多,则说明并发访问量非常大,正在处理过程中。
二、用户认证
auth_basic "欢迎信息";auth_basic_user_file "/path/to/user_auth_file";# user_auth_file内容格式username:password# 这里的密码为加密后的密码串,建议用htpasswd来创建文件htpasswd -c -m /path/to/.user_auth_file USERNAME
2.1 安装httpd-tools软件包
yum -y install httpd-tools
2.2 创建用户密钥文件
cd /usr/local/nginx/conf/htpasswd -c -m .user_auth_file ldh
2.3 配置nginx
# auth_basic_user_file必须用绝对路径server {listen 80;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location /status {stub_status on;auth_basic "Hello World";auth_basic_user_file "/usr/local/nginx/conf/.user_auth_file";}nginx -s reload
2.4 验证
浏览器访问192.168.100.10/status
三、https配置
环境说明:
nginx服务器 192.168.100.10
CA服务器 192.168.100.20
3.1 在CA服务器生成一对密钥
# 生成私钥cd /etc/pki/CA/(umask 077;openssl genrsa -out private/cakey.pem 2048)# 生成公钥openssl rsa -in private/cakey.pem -pubout
3.2 在CA服务器生成自签名证书
openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 1024 CN HB WH LQ linux ca root@example.com
3.3 在nginx服务器生成证书,并发送给CA
cd /usr/local/nginx/conf/ (umask 077;openssl genrsa -out httpd.key 2048)openssl req -new -key httpd.key -days 1024 -out httpd.csr CN HB WH LQ linux nginx root@example.comscp httpd.csr root@192.168.100.20:/etc/pki/CA/
3.4 在CA服务器上签署证书并发送给nginx
cd /etc/pki/CA/ touch index.txt echo 10 > serial openssl ca -in httpd.csr -out ./httpd.crt -days 1024scp httpd.crt root@192.168.100.10:/usr/local/nginx/conf/ scp cacert.pem root@192.168.100.10:/usr/local/nginx/conf/
3.5 nginx服务器配置https
server {listen 443 ssl;server_name localhost;ssl_certificate httpd.crt;ssl_certificate_key httpd.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;echo "Hello Hello" > /usr/local/nginx/html/index.htmlnginx -s reload