nginx配置
配置之前修改文件
vim /usr/local/nginx/conf/nginx
user nobody nobody; worker_processes 2; error_log /usr/local/nginx/logs/nginx_error.log crit; pid /usr/local/nginx/logs/nginx.pid; worker_rlimit_nofile 51200; events { use epoll; worker_connections 6000; } http { include mime.types; default_type application/octet-stream; server_names_hash_bucket_size 3526; server_names_hash_max_size 4096; log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]' ' $host "$request_uri" $status' ' "$http_referer" "$http_user_agent"'; sendfile on; tcp_nopush on; keepalive_timeout 30; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 8 4k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; client_max_body_size 10m; client_body_buffer_size 256k; client_body_temp_path /usr/local/nginx/client_body_temp; proxy_temp_path /usr/local/nginx/proxy_temp; fastcgi_temp_path /usr/local/nginx/fastcgi_temp; fastcgi_intercept_errors on; tcp_nodelay on; gzip on; gzip_min_length 1k; gzip_buffers 4 8k; gzip_comp_level 5; gzip_http_version 1.1; gzip_types text/plain application/x-javascript text/css text/htm application/xml; include vhost/*.conf; }
mkdir /usr/local/nginx/conf/vhost
cd /usr/local/nginx/conf/vhost
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
一.默认虚拟机
cd /usr/local/nginx/conf/vhost
配置一个default.conf文件
vim default.conf
server { listen 80 default_server; server_name aaa.com; index index.html index.htm index.php; root /data/nginx/default; }
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
创建一个访问文件
mkdir -p /data/nginx/default.conf
写入数据
echo " default server! " > /data/nginx/default/index.html
测试
curl -x127.0.0.1:80 bbb.com
default server!
curl -x127.0.0.1:80 aaa.com
如果在本机的虚拟机进行测试需要在本机的hosts文件进行映射虚拟机IP 及其 域名
二.用户认证
1.域名认证
用户认证需要用YUM安装httpd
yum install -y httpd
cd /usr/local/nginx/conf/vhost
vim test.com
server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/nginx/test.com; location / { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; } }
htpasswd -c /usr/local/nginx/conf/htpasswd wsw
New password:
Re-type new password:
Adding password for user wsw
/usr/local/nginx/sbin/nginx -s reload
mkdir /data/nginx/testcom
echo "test.com" > /data/nginx/test.com/index.html
测试
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
在本机hosts文件下映射了自己的IP及其域名第一次登录需要密码
我是因为之前登录了一次浏览器有缓存所以没密码
不加用户名
curl -x127.0.0.1:80 test.com
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.17.8</center>
</body>
</html>
加上用户名后
curl -uwsw -x127.0.0.1:80 test.com
Enter host password for user 'wsw':
test.com
2.目录认证
需要修改location后面的路径:
vim test.com.conf server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/nginx/test.com; location /admin/ { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; } }
创建目录
mkdir /data/nginx/test.com/admin
写入数据
echo "asdfadmin" > /data/nginx/test.com/admin/index.html
检查文件
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
测试:同域名认证一样需要用户名密码我之前输入过
3.URL认证
vim test.com.conf server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/nginx/test.com; location ~ admin.php { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; } }
测试:
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 test.com/admin.php
<html> <head><title>401 Authorization Required</title></head> <body> <center><h1>401 Authorization Required</h1></center> <hr><center>nginx/1.17.8</center> </body> </html>
三.域名重定向
配置
vim test.com.conf
server { listen 80; server_name test.com test2.com test3.com; index index.html index.htm index.php; root /data/nginx/test.com; if ($host != 'test.com' ){ rewrite ^(.*)$ http://test.com/$1 permanent; } }
测试
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 test2.com
<html> <head><title>301 Moved Permanently</title></head> <body> <center><h1>301 Moved Permanently</h1></center> <hr><center>nginx/1.17.8</center> </body> </html>
curl -x127.0.0.1:80 test2.com -I
HTTP/1.1 301 Moved Permanently Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:15:10 GMT Content-Type: text/html Content-Length: 169 Connection: keep-alive Location: http://test.com//
grep -A2 log_format /usr/local/nginx/conf/nginx.conf
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]' ' $host "$request_uri" $status' ' "$http_referer" "$http_user_agent"';
combined_realip为日志格式名字,$remote_addr为网站的用户的出口IP; $http_x_forwarded_for 为代理服务器的IP,如果使用了代理,则会记录IP # $time_local为当前时间;$host为主机名;$request_uri为访问的URL地址 # $status为状态码,$http_referer为referer地址,$http_user_agent为user_agent
vim test.com.conf
server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/nginx/test.com; access_log /tmp/1.log combined_realip; }
测试
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 test.com
cat /tmp/1.log
127.0.0.1 - [09/Sep/2021:10:21:19 -0400] test.com "/" 301 "-" "curl/7.29.0" 127.0.0.1 - [09/Sep/2021:10:21:42 -0400] test.com "/" 301 "-" "curl/7.29.0" 127.0.0.1 - [09/Sep/2021:10:23:49 -0400] test.com "/" 301 "-" "curl/7.29.0" 127.0.0.1 - [09/Sep/2021:10:24:41 -0400] test.com "/" 301 "-" "curl/7.29.0"
五.日志切割
写一个脚本
vim /usr/local/sbin/nginx_log_rotate.sh
#!/bin/bash ##假设nignx的日志存放路径为/data/logs/ d=`date -d "-1 day" +%Y%m%d` logdir="/tmp/" nginx_pid="/usr/local/nginx/logs/nginx.pid" cd $logdir for log in `ls *.log` do mv $log $log-$d done /bin/kill -HUP `cat $nginx_pid`
给与权限
chmod 755 /usr/local/sbin/nginx_log_rotate.sh
设置一个任务
crontab -e
0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh
查看日志文件
ls /tmp/
1.log ks-script-m9LmmW mysql.sock pear php-fcgi.sock yum.log
执行脚本文件
sh -x /usr/local/sbin/nginx_log_rotate.sh
++ date -d '-1 day' +%Y%m%d + d=20210908 + logdir=/tmp/ + nginx_pid=/usr/local/nginx/logs/nginx.pid + cd /tmp/ ++ ls 1.log yum.log + for log in '`ls *.log`' + mv 1.log 1.log-20210908 + for log in '`ls *.log`' + mv yum.log yum.log-20210908 ++ cat /usr/local/nginx/logs/nginx.pid + /bin/kill -HUP 617
查看日志
ls /tmp
1.log ks-script-m9LmmW pear yum.log-202109081.log-20210908 mysql.sock php-fcgi.sock
server { listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/nginx/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 7d; access_log off; } location ~ .*\.(js|css)$ { expires 12h; } access_log /tmp/1.log combined_realip; }
写入并创建测试文件
echo '111' > /data/nginx/test.com/1.js
echo '222' > /data/nginx/test.com/2.jpg
touch /data/nginx/test.com/1.jss
检查文件是否正确
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
清空日志数据
echo > /tmp/1.log
测试
curl -I -x127.0.0.1:80 test.com/1.js
HTTP/1.1 200 OK Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:42:50 GMT Content-Type: application/javascript Content-Length: 4 Last-Modified: Thu, 09 Sep 2021 14:42:07 GMT Connection: keep-alive ETag: "613a1d3f-4" Expires: Fri, 10 Sep 2021 02:42:50 GMT Cache-Control: max-age=43200 Accept-Ranges: bytes
curl -I -x127.0.0.1:80 test.com/2.jpg
HTTP/1.1 200 OK Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:43:06 GMT Content-Type: image/jpeg Content-Length: 4 Last-Modified: Thu, 09 Sep 2021 14:42:14 GMT Connection: keep-alive ETag: "613a1d46-4" Expires: Thu, 16 Sep 2021 14:43:06 GMT Cache-Control: max-age=604800 Accept-Ranges: bytes
curl -I -x127.0.0.1:80 test.com/1.jss
HTTP/1.1 200 OK Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:43:12 GMT Content-Type: application/octet-stream Content-Length: 0 Last-Modified: Thu, 09 Sep 2021 14:42:19 GMT Connection: keep-alive ETag: "613a1d4b-0" Accept-Ranges: bytes
cat /tmp/1.log
127.0.0.1 - [09/Sep/2021:10:42:50 -0400] test.com "/1.js" 200 "-" "curl/7.29.0" 127.0.0.1 - [09/Sep/2021:10:43:12 -0400] test.com "/1.jss" 200 "-" "curl/7.29.0"
七.防盗链
vim test.com.conf
server { listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/nginx/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; } location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ { expires 7d; valid_referers none blocked server_names *.test.com ; if ($invalid_referer) { return 403; } access_log off; } }
检查文件是否正确
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
测试
curl -x127.0.0.1:80 -e "http://aaa.com/1.txt" test.com/2.jpg -I
HTTP/1.1 403 Forbidden Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:54:04 GMT Content-Type: text/html Content-Length: 153 Connection: keep-alive
curl -x127.0.0.1:80 -e "http://test.com/1.txt" test.com/2.jpg -I
HTTP/1.1 200 OK Server: nginx/1.17.8 Date: Thu, 09 Sep 2021 14:54:20 GMT Content-Type: image/jpeg Content-Length: 4 Last-Modified: Thu, 09 Sep 2021 14:42:14 GMT Connection: keep-alive ETag: "613a1d46-4" Expires: Thu, 16 Sep 2021 14:54:20 GMT Cache-Control: max-age=604800 Accept-Ranges: bytes
八.访问控制
配置:vim /test.com.conf
server { listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/nginx/test.com; access_log /tmp/1.log combined_realip; location /admin/ { allow 192.168.100.100; allow 127.0.0.1; deny all; } }
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
测试
写入一个测试文件
echo "1234" > /data/nginx/test.com/admin/1.html
测试
curl -x192.168.100.100:80 test.com/admin/1.html
1234
curl -x127.0.0.1:80 test.com/admin/1.html
1234
使用指定IP curl都可以看到文件
主机无法访问文件
九.nginx解析php
配置
vim test.com.conf
fastcgi_pass用来指定php-fpm的地址 路径如果错误,则报错502
路径在/usr/local/php-fpm/etc/php-fpm.conf下
listen.mode = 666可以配置为# listen = 127.0.0.1:9000
server { listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/nginx/test.com; access_log /tmp/1.log combined_realip; location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/tmp/php-fcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /data/nginx/test.com$fastcgi_script_name; } }
配置测试文件
vim /data/nginx/test.com/3.php
<?php
phpinfo();
?>
测试
curl -x127.0.0.1:80 test.com/3.php
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
十.nginx代理
配置:
vim /usr/local/nginx/conf/vhost/proxy.conf
server { listen 80; server_name ask.apelearn.com; location / { proxy_pass http://47.104.7.242/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
测试:
curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
<html> <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.17.8</center> </body> </html>
刷新之后:
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
# # robots.txt for MiWen # User-agent: * Disallow: /?/admin/ Disallow: /?/people/ Disallow: /?/question/ Disallow: /account/ Disallow: /app/ Disallow: /cache/ Disallow: /install/ Disallow: /models/ Disallow: /crond/run/ Disallow: /search/ Disallow: /static/ Disallow: /setting/ Disallow: /system/ Disallow: /tmp/ Disallow: /themes/ Disallow: /uploads/ Disallow: /url-* Disallow: /views/ Disallow: /*/ajax/
十一.负载均衡
需要yum安装 bind-utils
配置测试:
dig www.baidu.com
; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.el7_9.7 <<>> www.baidu.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 17311 ;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.baidu.com. IN A ;; ANSWER SECTION: www.baidu.com. 250 IN CNAME www.a.shifen.com. www.a.shifen.com. 163 IN A 110.242.68.4 www.a.shifen.com. 163 IN A 110.242.68.3 ;; Query time: 4 msec ;; SERVER: 8.8.8.8#53(8.8.8.8) ;; WHEN: Thu Sep 09 11:28:49 EDT 2021 ;; MSG SIZE rcvd: 90
配置load.conf文件
upstream来指定多个web server
upstream后面的名字要和proxy_pass后面的名字相同
vim /usr/local/nginx/conf/vhost/load.conf
upstream baidu { ip_hash; server 220.181.38.149:80; server 220.181.38.150:80; } server { listen 80; server_name www.baidu.com; location / { proxy_pass http://baidu; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
刷新之前
curl -x127.0.0.1:80 www.baidu.com
default server!
刷新之后
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 www.baidu.com
<!DOCTYPE html> <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
十二.ssr
1.生成密钥对
rpm -qa openssl
openssl-1.0.2k-21.el7_9.x86_64
cd /usr/local/nginx/conf
生成私钥
openssl genrsa -des3 -out tmp.key 2048
Generating RSA private key, 2048 bit long modulus ......+++ ...........+++ e is 65537 (0x10001) Enter pass phrase for tmp.key: Verifying - Enter pass phrase for tmp.key:
删除刚才设置的密码
openssl rsa -in tmp.key -out aminglinux.key
Enter pass phrase for tmp.key:
writing RSA key
ls 查看是否生成
生成公钥
openssl req -new -key aminglinux.key -out aminglinux.csr
You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:66 State or Province Name (full name) []:liwei^H^H^H^C [root@localhost conf]# openssl req -new -key aminglinux.key -out aminglinux.csr You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:66 State or Province Name (full name) []:liwei Locality Name (eg, city) [Default City]:liwei Organization Name (eg, company) [Default Company Ltd]:cn^H^H^C [root@localhost conf]# openssl req -new -key aminglinux.key -out aminglinux.csr You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:66 State or Province Name (full name) []:lliwei Locality Name (eg, city) [Default City]:liwei Organization Name (eg, company) [Default Company Ltd]:cn Organizational Unit Name (eg, section) []:cn Common Name (eg, your name or your server's hostname) []:cn Email Address []:liwei@qq.com Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:123 string is too short, it needs to be at least 4 bytes long A challenge password []:1234 An optional company name []:1234
检查
openssl x509 -req -days 365 -in aminglinux.csr -signkey aminglinux.key -out aminglinux.crt
配置ssl
vim /usr/local/nginx/conf/vhost/ssl.conf
server { listen 443; server_name 123.com; index index.html index.php; root /data/nginx/123.com; ssl on; ssl_certificate aminglinux.crt; ssl_certificate_key aminglinux.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; }
/usr/local/nginx/sbin/nginx -t
nginx: [emerg] unknown directive "ssl" in/usr/local/nginx/conf/vhost/ssl.conf:7 nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
重新编译nginx
cd /usr/local/src/nginx-1.17.8
./configure --help |grep ssl
ith-http_ssl_module enable ngx_http_ssl_module --with-mail_ssl_module enable ngx_mail_ssl_module --with-stream_ssl_module enable ngx_stream_ssl_module --with-stream_ssl_preread_module enable ngx_stream_ssl_preread_module --with-openssl=DIR set path to OpenSSL library sources --with-openssl-opt=OPTIONS set additional build options for OpenSSL
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make && make install
启动nginx
/etc/init.d/nginx restart
netstat -ntlp
Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 3637/nginx: master tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1090/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1465/master tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 3637/nginx: master tcp6 0 0 :::3306 :::* LISTEN 10197/mysqld tcp6 0 0 :::22 :::* LISTEN 1090/sshd tcp6 0 0 ::1:25 :::* LISTEN
测试:
mkdir -p /data/nginx/123.com
echo "ssl test" > /data/nginx/123.com/index.html