
我有自己的 CentOS 6 和 nginx 的 VPS,我想啟用快取。為了測試它,如果它成功啟用,我使用 Google PageSpeed Insight。我的問題是,我在必須啟用快取以及可以設定圖像快取多長時間等方面沒有太多經驗。這就是我在互聯網上找到並到目前為止嘗試過的:
- 建立目錄:
/etc/nginx/sites-available
因為/etc/nginx/sites-enabled
它們不存在。 - 在此處連結建立的目錄:在文件末尾但在最後一個之前
/etc/nginx/nginx.conf
添加include /etc/nginx/sites-enabled/*;
}
建立文件
/etc/nginx/sites-available/my-site.com.conf
:server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 15d; } location ~* \.(pdf)$ { expires 30d; }
}
連結conf檔:
ln -s /etc/nginx/sites-available/my-site.com.conf /etc/nginx/sites-enabled/my-site.com.conf
- 做
service nginx restart
我使用 WordPress 網站。
因此,每當我使用 PageSpeed Insight 或其他 pagespeed 工具來測試我的頁面時,它都會說我沒有對 header.png、javascript 等使用快取。但即使我檢查顯示nginx -t
以下內容的配置文件,我也沒有收到一些錯誤:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
我是不是忘了什麼?
這是我完整的 nginx 設定:http://pastebin.com/wxnzzePT
來自default.conf
資料夾conf.d
:http://pastebin.com/KUH2tSrD
答案1
您需要將快取指令新增到您的default.conf
檔案中,並刪除您建立的這個新檔案。
僅當使用者使用http://localhost
.此外,與您的文件相比,您的新文件配置使用不同的路徑default.conf
。
此外,區塊root
內的指令location
也是不好的做法。
所以,你的default.conf
應該看起來像這樣:
#
# The default server
#
server {
listen 80 default_server;
server_name 213.165.xx.xx;
#charset koi8-r;
#access_log logs/host.access.log main;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
root /var/www/wordpress;
location / {
index index.html index.htm index.php;
try_files $uri $uri/ /index.php?q=$request_uri;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 15d;
}
location ~* \.(pdf)$ {
expires 30d;
}
location /admin {
auth_basic "Administrator Login";
auth_basic_user_file /var/www/admin/.htpasswd;
}
#!!! IMPORTANT !!! We need to hide the password file from prying eyes
# This will deny access to any hidden file (beginning with a .period)
location ~ /\. { deny all; }
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root /var/www/wordpress;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}