nginx

常见http状态码

状态码 描述
200 一切正常
301 永久重定向
302 临时重定向
401 用户名或密码错误
403 禁止访问
404 文件不存在
414 请求url头部过长
500 服务器内部错误
502 Bad Gateway

nginx部署

wget http://nginx.org/download/nginx-1.20.2.tar.gz
yum -y install gcc pcre-devel openssl-devel
useradd -s /sbin/nologin nginx
tar -xf nginx-1.20.2.tar.gz
cd nginx-1.20.2/
./configure --prefix=/usr/local/nginx --user=nginx --with-http_ssl_module --with-http_stub_status_module --with-stream
make && make install
/usr/local/nginx/sbin/nginx

脚本:

#!/bin/bash
#定义颜色函数
color(){
echo -e "\033[32m$1\033[0m"
}
color 此脚本用于安装或卸载nginx
read -p "请选择安装还是卸载nginx(1.安装|2.卸载):" x
case $x in
1)
wget http://nginx.org/download/nginx-1.20.2.tar.gz
useradd -s /sbin/nologin nginx
tar -xf nginx-1.20.2.tar.gz
yum -y install gcc make pcre-devel openssl-devel &> /dev/null
[ $? -ne 0 ] && color 依赖包未安装成功
cd nginx-1.20.2/
./configure --prefix=/usr/local/nginx --user=nginx --with-http_ssl_module --with-http_stub_status_module --with-stream &> /dev/null && make &> /dev/null && make install &> /dev/null
[ $? -eq 0 ] && color nginx已安装
/usr/local/nginx/sbin/nginx
netstat -ntulp | grep -q nginx
[ $? -eq 0 ] && color nginx服务已启动;;
2)
/usr/local/nginx/sbin/nginx -s stop
netstat -ntulp | grep -q nginx
[ $? -ne 0 ] && color nginx服务已停止
#find / -name nginx -exec rm -rf {} \;
rm -rf /usr/local/nginx
[ $? -eq 0 ] && color nginx已卸载;;
*)
echo "请输入正确的选项(1.安装|2.卸载)"
esac

nginx配置

用户认证

.. ..
server {
        listen       80;
        server_name  localhost;
        auth_basic "Input Password:";                        //认证提示符信息
        auth_basic_user_file  "/usr/local/nginx/pass";        //认证的密码文件
        location / {
            root   html;
            index  index.html index.htm;
        }
  }

生成密码文件,创建用户及密码

使用htpasswd命令创建账户文件,需要确保系统中已经安装了httpd-tools

yum -y install  httpd-tools
htpasswd -c /usr/local/nginx/pass   tom		 //创建密码文件
htpasswd  /usr/local/nginx/pass   jerry      //追加用户,不使用-c选项
/usr/local/nginx/sbin/nginx -s reload

基于域名的虚拟主机

    server {
        listen       80;
        server_name  www.a.com;
        location / {
            root   www;
            index  index.html index.htm;
        }
	}
mkdir /usr/local/nginx/www
echo "www" > /usr/local/nginx/www/index.html
curl www.a.com

SSL虚拟主机

    server {
        listen       443 ssl;
        server_name  www.a.com;

        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;
        }
    }
cd /usr/local/nginx/conf
openssl genrsa > cert.key									//生成私钥
openssl req -new -x509 -key cert.key > cert.pem				//生成证书
/usr/local/nginx/sbin/nginx -s reload

部署LNMP环境

首先安装nginx

yum -y install mariadb mariadb-server mariadb-devel php php-mysql php-fpm
systemctl start  mariadb php-fpm

修改php-fpm配置

FastCGI的内存消耗问题,一个PHP-FPM解释器将消耗约25M的内存

vim /etc/php-fpm.d/www.conf

[www]
listen = 127.0.0.1:9000            //PHP端口号
pm.max_children = 32                //最大进程数量
pm.start_servers = 15                //最小进程数量

修改nginx配置文件

        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            include        fastcgi.conf;
        }

创建PHP页面,测试LNMP架构能否解析PHP页面

cat >/usr/local/nginx/html/mysql.php<< 'EOF'
<?php
$mysqli = new mysqli('localhost','root','','mysql');
//注意:root为mysql数据库的账户名称,密码需要修改为实际mysql密码,无密码则留空即可
//localhost是数据库的域名或IP,mysql是数据库的名称
if (mysqli_connect_errno()){
    die('Unable to connect!'). mysqli_connect_error();
}
$sql = "select * from user";
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
    printf("Host:%s",$row[0]);
    printf("</br>");
    printf("Name:%s",$row[1]);
    printf("</br>");
}
?>
EOF

地址重写

访问a.html重定向到b.html

    server {
        listen       80;
        server_name  localhost;
        rewrite /a.html /b.html;					//当访问a时,跳转到b
        location / {
            root   html;
            index  index.html index.htm;
        }
	}

访问a.html重定向到b.html(跳转地址栏)**

    server {
        listen       80;
        server_name  localhost;
        rewrite /a.html /b.html redirect;			//redirect临时,permanent永久,last不再读其他rewrite语句,break不再读其他语句、结束请求		
        location / {
            root   html;
            index  index.html index.htm;
        }
	}

重定向到其他网站

    server {
        listen       80;
        server_name  localhost;
        rewrite ^/ http://www.baidu.com;				
        location / {
            root   html;
            index  index.html index.htm;
        }
	}

重定向到其他网站(带访问路径)

    server {
        listen       80;
        server_name  localhost;
        rewrite ^/(.*)$  http://www.baidu.com/$1;		//()保留,$1粘贴第一个()中内容		
        location / {
            root   html;
            index  index.html index.htm;
        }
	}

匹配请求头

    server {
        listen       80;
        server_name  localhost;
        if ($http_user_agent ~* firefox) {            //识别客户端firefox浏览器,~符号代表正则匹配,*符号代表不区分大小写
		rewrite ^(.*)$  /firefox/$1;
		}	
        location / {
            root   html;
            index  index.html index.htm;
        }
	}
    server {
        listen       80;
        server_name  localhost;
        if ($http_user_agent ~* "(Android|iPhone|Windows Phone|UC|Kindle)") {            
		rewrite ^(.*)$  /firefox/$1;
		}	
        location / {
            root   html;
            index  index.html index.htm;
        }
	}

nginx反向代理

upstream模块创建集群

#使用upstream定义后端服务器集群,集群名称任意(如webserver)
#使用server定义集群中的具体服务器和端口
upstream webserver {
                server 192.168.2.100:80;
                server 192.168.2.200:80;
        }
.. ..
server {
        listen        80;
        server_name  localhost;
            location / {
#通过proxy_pass将用户的请求转发给webserver集群
            proxy_pass http://webserver;
        }
}

健康检查、权重

.. ..
http {
.. ..
upstream webserver {
                server 192.168.2.100 weight=1 max_fails=1 fail_timeout=30;
                server 192.168.2.200 weight=2 max_fails=2 fail_timeout=30;
                server 192.168.2.101 down;
        }
#weight设置服务器权重值,默认值为1
#max_fails设置最大失败次数,测试服务器几次才确认服务器失败
#fail_timeout设置失败超时时间,单位为秒
#down标记服务器已关机,不参与集群调度
.. ..
server {
        listen        80;
        server_name  localhost;
            location / {
            proxy_pass http://webserver;
        }
}

调度算法

ip_hash
.. ..
http {
.. ..
upstream webserver {
#通过ip_hash设置调度规则为:相同客户端访问相同服务器
                 ip_hash;
                server 192.168.2.100 weight=1 max_fails=2 fail_timeout=10;
                server 192.168.2.200 weight=2 max_fails=2 fail_timeout=10;
        }
.. ..
server {
        listen        80;
        server_name  www.tarena.com;
            location / {
            proxy_pass http://webserver;
        }
}

nginx 配置4层代理

编译安装必须要使用--with-stream参数开启4层代理模块

stream {
            upstream backend {
               server 192.168.2.100:22;            //后端SSH服务器的IP和端口
               server 192.168.2.200:22;
}
            server {
                listen 12345;                    //Nginx监听的端口
                 proxy_pass backend;
             }
}
http {
.. ..
}

nginx优化

自定义404页面

.. ..
        charset utf-8;                    //仅在需要中文时修改该选项
error_page   404  /404.html;    //自定义错误页面(可以是图片)
.. ..

如何查看服务器状态信息

编译安装时使用--with-http_stub_status_module开启状态页面模块

… …
location /status {
                stub_status on;
                 #allow IP地址;
                 #deny IP地址;
        }
… …

优化Nginx并发量

修改nginx配置文件

.. ..
worker_processes  2;                    //根据CPU核心数量调整
events {
worker_connections 65535;        //每个worker最大并发连接数
}
.. ..

修改linux内核参数(最大文件数量)

ulimit -SHn	100000				//临时修改软硬限制
永久修改:
cat >>/etc/security/limits.conf<< 'EOF'
*               soft    nofile            100000
*               hard    nofile            100000
EOF

优化Nginx数据包头缓存

用脚本创建一个超长url地址

#!/bin/bash
URL=http://192.168.4.5/index.html?
for i in {1..5000}
do
    URL=${URL}v$i=$i
done
curl $URL

修改Nginx配置文件,增加数据包头部缓存大小

.. ..
http {
client_header_buffer_size    200k;        //默认请求包头信息的缓存    
large_client_header_buffers  4 200k;        //最大请求包头部信息的缓存个数与容量
.. ..
}

设置客户端缓存时间

server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
	location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
	expires        30d;            //定义客户端缓存时间为30天
	}
}

Session共享

构建memcached服务

memcached命令:

  • add name 0 180 10 //变量不存在则添加
  • set name 0 180 10 //添加或替换变量
  • replace name 0 180 10 //替换
  • get name //读取变量
  • delete name //删除变量
  • flush_all //清空所有
  • 提示:0表示不压缩,180为数据缓存时间,10为需要存储的数据字节数量。
yum -y  install   memcached   telnet
systemctl  start  memcached

PHP实现session共享

yum -y install  php-pecl-memcache
sed -i '/^php_value\[session.save_handler\]/s/files/memcache/' /etc/php-fpm.d/www.conf
sed -i '/^php_value[session.save_path]/s%/var/lib/php/session%"tcp://192.168.2.5:11211"%' /etc/php-fpm.d/www.conf				//指定memcached服务器
systemctl  restart  php-fpm

nginx搭建ftp服务器

user nobody;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;


    server {
        listen       80;
        server_name  localhost;
        charset utf-8;
        autoindex on;             # 显示目录
        autoindex_exact_size on;  # 显示文件大小
        autoindex_localtime on;   # 显示文件时间

        location /soft/ {
        alias   /var/ftp/;
        index index.html index.htm;
         }



    }


}
posted @ 2022-01-01 07:55  barry_zou  阅读(84)  评论(1)    收藏  举报