一、优化nginx配置
1、日志配置优化
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$host"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
}
2、静态文件缓存配置
http {
#文件缓存大小为200MB,文件缓存有效期为1天
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=1d max_size=200m;
#指定需要缓存的文件类型和请求方法
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 304 1d;
server {
location / {
#启用文件缓存
proxy_cache my_cache;
proxy_cache_bypass $http_pragma;
proxy_cache_revalidate on;
#指定缓存的文件类型
proxy_cache_valid 200 60m;
proxy_cache_valid 404 1m;
}
}
}
3、负载均衡配置
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
}
二、启用gzip压缩
在nginx配置文件中添加以下内容
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
server {
...
}
}
三、启用SSL证书
1、生成证书
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
2、在nginx配置文件中启用SSL证书
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/server.crt;
ssl_certificate_key /path/to/server.key;
location / {
...
}
}
四、使用fastcgi代理
1、配置php-fpm
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm.sock;
#以下是$fastcgi_param的值,可以根据实际情况修改
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PHP_FLAG 'short_open_tag=On';
fastcgi_param PHP_VALUE 'max_execution_time=100';
fastcgi_param PHP_ADMIN_VALUE 'open_basedir=/usr/share/nginx/html:/tmp/:/var/tmp/:/var/www/';
fastcgi_index index.php;
include fastcgi_params;
}
2、配置nginx代理
location / {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
五、使用HTTP/2协议
在nginx配置文件中启用http2模块
http {
...
server {
listen 443 ssl http2;
...
}
}
原创文章,作者:MYBHW,如若转载,请注明出处:https://www.506064.com/n/330404.html