http {
include /etc/nginx/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"'
'"$proxy_host" "$upstream_addr"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
# 开启gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
# 负载均衡 这里可以是多个cos桶地址即可
upstream static_env {
server xxx;
server xxx;
}
# map 设置变量映射 第一个变量指的是要通过映射的key值 Accpet 第二个值的是变量别名
map $http_accept $webp_suffix {
# 默认为 空字符串
default "";
# 正则匹配如果Accep含有webp字段 设置为.webp值
"~*webp" ".webp";
}
server {
listen 8888;
absolute_redirect off; #取消绝对路径的重定向
#网站主页路径。此路径仅供参考,具体请您按照实际目录操作。
root /usr/share/nginx/html;
location / {
index index.html index.htm;
proxy_set_header Host $host;
try_files $uri $uri/ /index.html;
add_header Cache-Control 'no-cache, max-age=0';
}
# favicon.ico
location = /favicon.ico {
log_not_found off;
access_log off;
}
# robots.txt
location = /robots.txt {
log_not_found off;
access_log off;
}
#
location ~* \.(png|jpe?g)$ {
# Pass WebP support header to backend
# 如果header头部中支持webp
if ($webp_suffix ~* webp) {
# 先尝试找是否有webp格式图片
rewrite ^/(.*)\.(png|jpe?g)$ /$1.webp break;
# 找不到的话 这里捕获404错误 返回原始错误 注意这里的=号 代表最终返回的是@static_img的状态吗
error_page 404 = @static_img;
}
proxy_intercept_errors on;
add_header Vary Accept;
proxy_pass http://static_env;
proxy_set_header Host $http_host;
expires 7d;
access_log off;
}
location @static_img {
#set $complete $schema $server_addr $request_uri;
rewrite ^/.+$ $request_uri break;
proxy_pass http://static_env;
proxy_set_header Host $http_host;
expires 7d;
}
# assets, media
location ~* \.(?:css(\.map)?|js(\.map)?|gif|svg|jfif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
proxy_pass http://static_env;
proxy_set_header Host $http_host;
expires 7d;
access_log off;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
|