nginx服务器配置了ngx_pagespeed的模块之后有可能会出现资源加载错误404未找到的情况。Pagespeed重命名静态资源(如图像、CSS等)文件名以标记为已优化,在某些情况下,Pagespeed优化的网页资源返回404未找到,并且在几次浏览器刷新后,它们最终会加载。在这种情况下,Pagespeed仍在优化网页资源的过程中。如果服务器使用的是nginx则可以如下配置:
## Pagespeed optimized resources that returns 404, redirect to original resource location ~ (.+)/x(.+),(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle resources with query string and Pagespeed optimized resources with # file name prefixed with x (eg. xMyImage.png,qitok=qwer.pagespeed.asdf.webp) error_page 404 = @orig_resource; set $orig_resource_uri $1/$2?$3; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+),(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle resources with query string error_page 404 = @orig_resource; set $orig_resource_uri $1?$2; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+)/x(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle Pagespeed optimized resources with file name prefixed with x # (eg. xMyImage.png.pagespeed.asdf.webp) error_page 404 = @orig_resource; set $orig_resource_uri $1/$2; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Default handler error_page 404 = @orig_resource; set $orig_resource_uri $1; try_files $uri $uri/ $orig_resource_uri; } ## Redirect Pagespeed optimized resources that returns 404 to ## original resource. location @orig_resource { return 302 $scheme://$server_name$orig_resource_uri; }
上面的脚本将捕获Pagespeed重命名的资源静态文件,然后首先检查是否存在Pagespeed重命名的源静态文件,如果没有找到,则重定向到原始资源。
建议按以下方式放置脚本:
server { # ... your server context script location / { # ... some location context script ## Pagespeed optimized resources that returns 404, redirect to original resource location ~ (.+)/x(.+),(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle resources with query string and Pagespeed optimized resources with # file name prefixed with x (eg. xMyImage.png,qitok=qwer.pagespeed.asdf.webp) error_page 404 = @orig_resource; set $orig_resource_uri $1/$2?$3; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+),(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle resources with query string error_page 404 = @orig_resource; set $orig_resource_uri $1?$2; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+)/x(.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Handle Pagespeed optimized resources with file name prefixed with x # (eg. xMyImage.png.pagespeed.asdf.webp) error_page 404 = @orig_resource; set $orig_resource_uri $1/$2; try_files $uri $uri/ $orig_resource_uri; } location ~ (.+)\.pagespeed\.[\.\-_[:alnum:]]+$ { # Default handler error_page 404 = @orig_resource; set $orig_resource_uri $1; try_files $uri $uri/ $orig_resource_uri; } } ## Redirect Pagespeed optimized resources that returns 404 to ## original resource. location @orig_resource { return 302 $scheme://$server_name$orig_resource_uri; } }