search
HomeBackend DevelopmentPHP Tutorialnginx cache configuration

nginx cache configuration

Nginx supports Squid-like caching function starting from version 0.7.48. This cache treats the URL and related combinations as Key, uses md5 encoding and hashing and stores them on the hard disk, so it can support any URL link and also supports non-200 status codes such as 404/301/302. Although the current official Nginx web cache service can only set the expiration time for the specified URL or status code, and does not support the Squid-like PURGE instruction to manually clear the specified cache page, however, through a third-party Nginx module, the cache of the specified URL can be cleared. . IT Network, http://www.it.net.cn

Nginx’s Web caching service is mainly composed of proxy_cache related instruction set and fastcgi_cache related instruction set. The former is used for reverse proxy, which affects the back-end content source server. Cache, the latter is mainly used to cache FastCGI dynamic programs. The functionality of both is basically the same.

In the latest Nginx 0.8.32 version, proxy_cache and fastcgi_cache are relatively complete. Together with the third-party ngx_cache_purge module (used to clear the cache of the specified URL), it can completely replace Squid. We have been using Nginx's proxy_cache caching function in the production environment for more than two months. It is very stable and the speed is not inferior to Squid.

In terms of functionality, Nginx already has the Web cache acceleration function and the function of clearing the specified URL cache that Squid has. In terms of performance, Nginx's utilization of multi-core CPUs is much better than Squid. In addition, Nginx is much more powerful than Squid in terms of reverse proxy, load balancing, health check, back-end server failover, rewrite, and ease of use. This allows one Nginx to be used as a "load balancing server" and a "Web cache server" at the same time.

1. Compile and install Nginx load balancing and caching server under Linux:
Linux learning, http://linux.it.net.c

ulimit -SHn 65535
wget ftp://ftp.csx .cam.ac.uk/pub/software/programming/pcre/pcre-8.00.tar.gz
tar zxvf pcre-8.00.tar.gz


cd pcre-8.00/
./configure
make && make install
cd ../

wget http://labs.frickle.com/files/ngx_cache_purge-1.0.tar.gz
tar zxvf ngx_cache_purge-1.0.tar.gz

wget http://nginx.org/download/nginx-0.8.32. tar.gz
tar zxvf nginx-0.8.32.tar.gz
cd nginx-0.8.32/
./configure --user=www --group=www --add-module=../ngx_cache_purge-1.0 - -prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
cd ../ IT Network, http://www.it.net.cn

2, /usr/local/nginx/conf/nginx.conf The configuration file content is as follows:
IT Network, http://www.it.net.cn

user www www;

worker_processes 8;

error_log / usr/local/nginx/logs/nginx_error.log crit; IT Network, http://www.it.net.cn

pid /usr/local/nginx/logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535; /octet-stream ;

Linux learning, http:// linux.it.net.cn



#charset utf-8;

server_names_hash_bucket_size 128;

client_header_buffer_size 32k;

large_client_header_buffers 4 32k;
client_max_body_size 300m;

sendfile on; tcp_nopush on;

keepalive_timeout 60;

IT Network, http://www.it.net.cn


tcp_nodelay on;

client_body_buffer_size 512k;
proxy_connect_timeout 5;
proxy_read_timeout 60 ;
proxy_send_timeout 5;

proxy_buffer_size 16k;

proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k;

IT Network, http://www.it.net.cn

gzip on;
gzip_min_length 1k;
g zip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;

#Note: The paths specified by proxy_temp_path and proxy_cache_path must be in the same partition
proxy_temp_path /data0/proxy_temp_dir;
#Set the name of the Web cache area to cache_one, the memory cache space size to 200MB, content that has not been accessed in 1 day will be automatically cleared, and the hard disk cache The space size is 30GB.
proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_z inactive=1d max_size=30g;

upstream backend_server {
server 192.168.8.43:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.8.44:80 weight= 1 max_fails=2 fail_timeout=30s;
server 192.168.8.45:80 weight=1 max_fails=2 fail_timeout=30s;
}

server
{
listen 80;
server_name www.it.net.cn 192.168.8.42;
index index.html index.htm;
root /data0/htdocs/www;

location /
{
Another server for failover.
            proxy_next_upstream http_502 http_504 error timeout invalid_header;
          proxy_cache cache_one; 
      #Set different cache times for different HTTP status codes
                      proxy_cache_valid     200 304 12h; 
    ​​ #Combine the domain name, URI, and parameters to form the Key value of the Web cache. Nginx uses the Key Value hash, store cache content in the second-level cache directory
      proxy_cache_key $host$uri$is_args$args;
    proxy_set_header Host   $host;


        proxy_set_header X-Forwarded-For   $remote_addr;
    proxy_pass http://back end_server;
expires   1d;
  }
 ​​​​​​​​ # Used to clear the cache. Suppose a URL is http://192.168.8.42/test.txt. You can clear the URL by accessing http://192.168.8.42/purge/test.txt cache.
Location ~ /purge(/.*)
{
#Set only the specified IP or IP segment to clear the URL cache.
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all; proxy_cache_purge cache_one $host$1$is_args $args;
}
  # Dynamic applications with extensions ending in .php, .jsp, .cgi are not cached.
location ~ .*.(php|jsp|cgi)?$

{
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://backend_server;
}
access_log off;
}
}
Linux learning, http://linux.it.net.cn

The above introduces the nginx cache configuration, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),