一、優化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/zh-hk/n/330404.html