Nginx优化
自定义错误页面
200 | 一切正常 |
---|---|
400 | 请求语法错误 |
401 | 访问被拒绝(账户或密码错误) |
403 | 资源不可用,服务器文件/目录权限不足导致 |
404 | 无法找到指定位置的资源 |
414 | 请求URL头部太长 |
500 | 服务器内部错误 |
502 | 服务器作为网关时,为了完成请求访问下一个服务器,但该服务器返回非法应答 |
http{
fastcgi_intercept_error on ;
server{
error_page 404 /40x.html ;
location = /40x.html{
root html ;
}
error_page 500 502 503 504 /50x.html ;
location = /50x.html{
root html ;
}
}
}
Nginx状态页面 status 模块
./configure --with-http_stub_status_module 开启模块功能
修改配置文件
location /status{
stub_status on ;
# allow IP地址 ;
# deny IP地址 ;
}
全局配置优化
调整进程数量
worker_processes 2 ; //与CPU核心数量一致
Event 模块优化
max_client = work_processes x worker_connections
event{
worker_connections 100000 ; //每个worker最大并发连接数
}
修改Linux系统内核参数(最大文件数)
ulimit -SHn 8192 //设置软硬限制(临时有效)
vim /etc/security/limits.conf
* soft nofile 8192
* hard nofile 8192
#用户/组 硬限制/软限制 限制的项目 限制的值
HTTP模块优化
1. 连接时间
2. 压缩文件
3. 请求包头容量大小
4. 服务器缓存文件
5. 客户端缓存文件静态文件
http{
keepalive_tmeout 10 ; //保持连接的超时时间
gzip on ;
gzip_min_length 1000 ;
gzip_comp_level 4 ;
gzip_types text/plain text/css applacation/json application/x-javascript text/xml application/xml application/xml+rss text/javascript ;
client_header_buffer_size 1k ; //请求包头的信息缓存
large_client_header_buffer_size 4 4k ; //最大请求包头部信息的缓存个数与容量
//先根据client_header_buffers分配,如果不够,再根据large分配
open_file_cache max=2000 inactive=20s ; //最大缓存2000个文件句柄,关闭20s无请求的文件句柄
open_file_cache_valid 60s ; //文件句柄的有效时间60s,60s后过期
open_file_cache_min_uses 5 ; //访问超过5次才会被缓存
open_file_cache_errors off ;
location ~*\.(jpg|jpeg|gif|png|css|js|ico|xml)${
exires 30d ; // 客户端缓存时间30天
}
其他 location
......
}
日志切割(计划任务+脚本)
#!/bin/bash
date=$(date +%Y%y%d)
logpath='/usr/local/nginx/logs'
mv ${logpath}/access.log ${logpaht}/access-${date}.log
mv ${logpath}/error.log ${logpath}/error-${date}.log
kill -USR1 $(cat ${logpath}nginx.pid)
03 03 * * 5 /usr/local/nginx/logback.sh
图片自动适应大小
http://192.168.1.11/img/w_200/h_400/t.jpg
./configure --with-http_image_module
location ~* ^/img/w_(\d+)/h_(\d+)/(.*)${
rewrite /img/w_(\d+)/h_(\d+)/(.*)$ /image/$3 break ;
image_filter_buffer 32M ;
image_filter resize $1 $2 ;
}
配置文件添加头部信息,方便web集群排错
add_header Cluster_id $HOSTNAME ;
PHP动态网页缓存
http:{
fastcgi_temp_path /var/cache/nginx/fcgi; //缓存目录
fastcgi_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=PHP_CACHE:128m inactive=300s max_size=1g;
//两级1、2 缓存空间大小128m 生命周期300s 最大空间1G
fastcgi_connect_timeout 180; //连接超时时间
fastcgi_send_timeout 60;
fastcgi_read_timeout 120;
fastcgi_buffer_size 512k;
fastcgi_buffers 16 128k;
fastcgi_busy_buffers_size 1024k;
fastcgi_temp_file_write_size 512k;
fastcgi_cache PHP_CACHE;
#fastcgi_cache_methods POST; // post方式(提交交易数据)不缓存
fastcgi_cache_valid 200 2s; // 正常访问,缓存时间2秒,可用5s/5m
fastcgi_cache_valid 302 30m;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 5s;
fastcgi_cache_min_uses 5;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$server_name$uri$is_args$args;