
У меня есть собственный VPS с CentOS 6 и nginx, и я хочу включить кэширование. Чтобы проверить его, если оно успешно включено, я использую 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, javascripts и т. д. Но я не получаю никаких ошибок, даже если я проверяю файлы конфигурации, 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;
#}
}