nginx
nginx是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。
nginx安装
关闭防火墙和selinux
[root@yxr ~]# setenforce 0
[root@yxr ~]# sed -ri 's/(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@yxr ~]# systemctl stop firewalld
[root@yxr ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
创建系统用户nginx
[root@yxr ~]# useradd -r -M -s /sbin/nologin nginx
[root@yxr ~]# id nginx
uid=998(nginx) gid=996(nginx) groups=996(nginx)
安装依赖环境
[root@yxr ~]# yum -y install pcre-devel openssl openssl-devel gd-devel
[root@yxr ~]# yum -y groups mark install 'Development Tools'
[root@yxr ~]# yum grouplist
创建日志存放目录
[root@yxr ~]# mkdir -p /var/log/nginx
[root@yxr ~]# chown -R nginx.nginx /var/log/nginx
下载nginx
[root@yxr ~]# cd /usr/src/
[root@yxr src]# yum install wget
[root@yxr src]# wget http://nginx.org/download/nginx-1.12.0.tar.gz
[root@yxr src]# tar xf nginx-1.12.0.tar.gz
[root@yxr src]# cd nginx-1.12.0/
[root@yxr nginx-1.12.0]# ./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-debug \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_image_filter_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log
[root@yxr nginx-1.12.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
nginx安装后配置
配置环境变量
[root@yxr ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@yxr ~]# source /etc/profile.d/nginx.sh
启动nginx
[root@yxr ~]# nginx
[root@yxr ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
安装完成之后,通过浏览器输入自己的IP,可以访问,这里我的IP是192.168.228.23,出现如下界面就是成功,如图:
nginx的配置文件详解
主配置文件:/usr/local/nginx/conf/nginx.conf
[root@yxr ~]# vim /usr/local/nginx/conf/nginx.conf
user nginx; //指定运行worker进程的用户和组
worker_processes 3; //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask 00000100 00000010 00000001; //此行是我添加,可以优化性能的配置参数,将进程绑定到某cpu中,避免频繁刷新缓存
error_log logs/error.log;
pid logs/nginx.pid; //指定nginx守护进程的pid文件
events {
worker_connections 1024; //每个进程能够接受的最大连接数
}
http { //协议级别
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
#gzip on;
server { //服务器级别,每个server类似于httpd中的一个<VirtualHost>
listen 80;
server_name localhost;
location / { //请求级别,类似于httpd中的<location>,用于定义URL与本地文件系统的映射关系
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000; //定义反向代理
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.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;
# }
#}
}
访问控制
用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用于空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
[root@yxr ~]# vim /usr/local/nginx/conf/nginx.conf
...
location / {
root html;
index index.html index.htm;
allow 192.168.228.1;
deny all;
}
...
[root@yxr ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr ~]# nginx -s reload
验证结果:
拒绝本机IP访问
[root@yxr ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
deny 192.168.228.1;
allow all;
}
root@yxr ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr ~]# nginx -s reload
验证结果:
基于认证
创建一个存放用户认证的目录
[root@yxr ~]# cd /usr/local/nginx/
[root@yxr nginx]# mkdir auth
[root@yxr nginx]# ll
total 4
drwxr-xr-x. 2 root root 6 Sep 2 10:58 auth
drwx------. 2 nginx root 6 Sep 2 10:05 client_body_temp
drwxr-xr-x. 2 root root 4096 Sep 2 10:58 conf
drwx------. 2 nginx root 6 Sep 2 10:05 fastcgi_temp
drwxr-xr-x. 2 root root 40 Sep 2 10:02 html
drwxr-xr-x. 2 root root 58 Sep 2 10:23 logs
drwx------. 2 nginx root 6 Sep 2 10:05 proxy_temp
drwxr-xr-x. 2 root root 19 Sep 2 10:02 sbin
drwx------. 2 nginx root 6 Sep 2 10:05 scgi_temp
drwx------. 2 nginx root 6 Sep 2 10:05 uwsgi_temp
安装生成密码的命令
[root@yxr nginx]# yum provides *bin/htpasswd
[root@yxr nginx]# yum -y install httpd-tools
创建登录nginx的用户和密码
[root@yxr nginx]# htpasswd -c -m /usr/local/nginx/auth/.user_auth_file tom
New password:
Re-type new password:
Adding password for user tom
编辑配置文件
location / {
root html;
index index.html index.htm;
auth_basic "welcome there";
auth_basic_user_file ../auth/.user_auth_file;
}
测试语法加载nginx
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
验证结果:
https配置
1.生成私钥:CA的配置文件:/etc/pki/tls/openssl.cnf
[root@yxr nginx]# cd /etc/pki/CA/
[root@yxr CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048) #生成密钥
[root@yxr CA]# openssl rsa -in private/cakey.pem -pubout #提取公钥
2.CA生成签署证书
[root@yxr CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365 #生成自签署证书
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]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:www.yaoxiaorong.com
Organizational Unit Name (eg, section) []:www.yaoxiaorong.com
Common Name (eg, your name or your server's hostname) []:www.yaoxiaorong.com
Email Address []:162.@qq.com
[root@yxr CA]# openssl x509 -text -in cacert.pem #读出cacert.pem证书的内容
[root@yxr CA]# mkdir certs newcerts crl
mkdir: cannot create directory ‘certs’: File exists
mkdir: cannot create directory ‘newcerts’: File exists
mkdir: cannot create directory ‘crl’: File exists
[root@yxr CA]# ls
cacert.pem certs crl newcerts private
[root@yxr CA]# touch index.txt && echo 01 > serial
[root@yxr CA]# ls
cacert.pem certs crl index.txt newcerts private serial
[root@yxr CA]# cat serial
01
3.客户端(nginx)生成密钥
[root@yxr CA]# cd /usr/local/nginx/
[root@yxr nginx]# mkdir ssl
[root@yxr nginx]# cd ssl/
[root@yxr ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
.....+++
....................+++
e is 65537 (0x10001)
4.客户端生成证书签署请求
[root@yxr ssl]# openssl req -new -key nginx.key -days 365 -out nginx.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]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:www.yaoxiaorong.com
Organizational Unit Name (eg, section) []:www.yaoxiaorong.com
Common Name (eg, your name or your server's hostname) []:www.yaoxiaorong.com
Email Address []:162.@qq.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@yxr ssl]# openssl ca -in ./nginx.csr -out nginx.crt -days 365
[root@yxr ssl]# ls
nginx.crt nginx.csr nginx.key
编辑配置文件
# HTTPS server
# #以下的注释#全部取消
server {
listen 443 ssl;
server_name www.yaoxiaorong.com; #编辑此处
ssl_certificate /usr/local/nginx/ssl/nginx.crt; #编辑此处
ssl_certificate_key /usr/local/nginx/ssl/nginx.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;
}
}
}
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
在本机的C:\Windows\System32\drivers\etc加入IP与域名,创建映射关系,然后进行验证:
开启状态界面
[root@yxr nginx]# vim conf/nginx.conf
location /status {
stub_status on;
allow 192.168.228.1;
deny all;
root html;
index index.html index.htm;
}
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
验证结果:
rewrite
[root@yxr nginx]# cd html
[root@yxr html]# mkdir images
[root@yxr html]# cd images/
[root@yxr images]# ls
1.jpg
[root@yxr nginx]# vim conf/nginx.conf
//添加以下内容
location /images {
root html;
index index.html;
}
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
验证结果:
2.将images目录重命名imgs
[root@yxr nginx]# cd html
[root@yxr html]# mv images imgs
[root@yxr html]# ls
50x.html imgs index.html
[root@yxr nginx]# vim conf/nginx.conf
location /images {
root html;
index index.html index.htm;
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
}
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
验证结果:
3.映射网页验证
location /imgs {
root html;
index index.html index.htm; rewrite ^/imgs/(.*)$ http://www.baidu.com/index.html redirect;
}
[root@yxr nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr nginx]# nginx -s reload
验证结果:
if
应用场景:
server段
location段
常见的conditon
变量名(变量值为空串或者以“0”开始,为false;其他的均为true)
正则表达式的模式匹配操作
~:区分大小写的模式匹配检查
~*:不区分大小写的模式匹配检查
!~和!~*:对上面两种测试取反
测试指定路径为文件的可能性(-f,!-f)
测试指定路径为目录的可能性(-d,!-d)
测试文件的存在性(-e,!-e)
检查文件是否有执行权限(-x,!-x)
以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
基于浏览器实现分离案例—谷歌
[root@arongya ~]# cd /usr/local/nginx/html/
[root@arongya html]# mkdir Chrome
[root@arongya html]# mv imgs Chrome
[root@arongya html]# cd Chrome/
[root@arongya Chrome]# ls
imgs
修改/usr/local/nginx/conf/nginx.conf文件让它运行谷歌访问,不允许其他浏览器访问
···
location / {
root html;
index index.html index.htm;
}
location /images {
if ($http_user_agent ~ Chrome) {
rewrite ^/images/(.*)$ /Chrome/imgs/$1 break;
}
}
···
[root@arongya Chrome]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya Chrome]# nginx -s reload
验证结果,谷歌可以访问
其他浏览器不能访问
检查日志文件
[root@arongya Chrome]# cd /var/log
[root@arongya log]# cd nginx/
[root@arongya nginx]# ls
access.log error.log
[root@arongya nginx]# cat access.log
192.168.228.1 - - [30/Aug/2018:14:53:02 +0800] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
192.168.228.1 - - [30/Aug/2018:14:53:03 +0800] "GET /favicon.ico HTTP/1.1" 404 571 "http://192.168.228.30/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
检查日志文件
[root@arongya Chrome]# cd /var/log
[root@arongya log]# cd nginx/
[root@arongya nginx]# ls
access.log error.log
[root@arongya nginx]# cat access.log
192.168.228.1 - - [30/Aug/2018:14:53:02 +0800] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
192.168.228.1 - - [30/Aug/2018:14:53:03 +0800] "GET /favicon.ico HTTP/1.1" 404 571 "http://192.168.228.30/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
基于浏览器实现分离案例
if ($http_user_agent ~ Firefox) {
rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
防盗链案例
套路只需要把域名修改
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referer none clocked www.yaoxiaorong.com;
if ($invalid_referer) {
rewrite ^/ http://www.yaoxiaorong.com/403.html;
}
}
反向代理与负载均衡
反向代理(Reverse Proxy)是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端。
nginx通常被用作后端服务器的反向代理,方便实现动静分离和负载均衡。
nginx通过upsream模块来实现简单的负载均衡,upstream需要定义在http段内在upstream段内,定义一个服务器列表,默认的方式是轮询。
如果确定同一个访问者发出请求总是由同一个后端服务器来处理,可以设置ip-hash。
ip_hash每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题.
分别在开两台虚拟机,一个下载nginx,一个在下载apache,步骤略。然后关闭防火墙和seliux.
192.168.228.23这台虚拟机安装nginx,步骤略:
[root@yxr ~]# setenforce 0
[root@yxr ~]# systemctl stop firewalld
[root@yxr ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
192.168.228.21这台虚拟机安装apache,步骤略:
[root@yaoxiaorong ~]# setenforce 0
setenforce: SELinux is disabled
[root@yaoxiaorong ~]# systemctl stop firewalld
[root@yaoxiaorong ~]# systemctl disable firewalld
192.168.228.23在/use/local/nginx/html创建网页内容:
[root@yxr nginx-1.12.0]# cd /usr/local/nginx/html/
[root@yxr html]# ls
50x.html index.html
[root@yxr html]# echo "123,yaoxiaorong" >> index.html
192.168.228.21在/var/www/html站点文档目录创建网页内容:
[root@yaoxiaorong ~]# cd /var/www/html/
[root@yaoxiaorong html]# ls
[root@yaoxiaorong html]# echo "hello yaoxiaorong" >> index.html
[root@yaoxiaorong html]# ls
index.html
在192.168.228.30/usr/local/nginx/conf/nginx.conf修改配置文件
···
upstream web {
server 192.168.228.23;
server 192.168.228.21;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://web;
}
···
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload
验证实验结果:
修改端口看是否能访问
192.168.228.21
[root@yaoxiaorong html]# vim /etc/httpd/conf/httpd.conf
#Listen 12.34.56.78:80
Listen 8090
[root@yaoxiaorong html]# systemctl restart httpd
192.168.228.23
[root@yxr ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 8080;
server_name localhost;
[root@yxr ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@yxr ~]# nginx -s reload
192.168.228.30
[root@arongya nginx]# vim /usr/local/nginx/conf/nginx.conf
...
upstream web {
server 192.168.228.23:8080;
server 192.168.228.21:8090;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://web;
}
...
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload
端口改变,但是依然可以访问,跟之前的结果一样
将IP_hash加入/usr/local/nginx/conf/nginx.conf配置文件,然后在访问浏览器,修改完成重新加载
upstream web {
ip_hash;
server 192.168.228.23:8080;
server 192.168.228.21:8090;
}
验证结果: