Включить кэширование на nginx

Включить кэширование на nginx

У меня есть собственный VPS с CentOS 6 и nginx, и я хочу включить кэширование. Чтобы проверить его, если оно успешно включено, я использую Google PageSpeed ​​Insight. Моя проблема в том, что у меня нет большого опыта, где мне нужно включить кэширование и где я могу установить, как долго изображение, например, будет кэшироваться и т. д. Вот что я нашел в интернете и попробовал на данный момент:

  1. создание каталогов: /etc/nginx/sites-availableи /etc/nginx/sites-enabledпотому что их почему-то не существовало.
  2. Связываем созданные каталоги здесь: /etc/nginx/nginx.confс добавлением include /etc/nginx/sites-enabled/*;в конец файла, но перед последним}
  3. Создание файла /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;
    }
    

    }

  4. Связываем файл conf:ln -s /etc/nginx/sites-available/my-site.com.conf /etc/nginx/sites-enabled/my-site.com.conf

  5. делать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;
    #}
}

Связанный контент