I am starting to learn bash script and need to write a script to install fastcgi_cache
on NGINX. I need to replace the default location for PHP with the one with the fastcgi_cache
settings.
To be clear, I need to replace this:
location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
With this:
location ~ .php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock ;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
access_log /var/log/nginx/$SITE_URL.cache.log cache;
fastcgi_cache_key "$mobile$scheme$request_method$host$request_uri";
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache WORDPRESS;
add_header X-Cache-Status $upstream_cache_status ;
}
I believe this can be done with sed
, but I cannot find a way to do it. I managed to make it work with a sort of workaround, like this:
if [ -f "/etc/nginx/sites-enabled/$SITE_URL" ]
then
sed -i.bak '/fastcgi_params;/c\
include fastcgi_params;\
\
access_log /var/log/nginx/'$SITE_URL'.cache.log cache;\
fastcgi_cache_key "$mobile$scheme$request_method$host$request_uri";\
fastcgi_cache_bypass $skip_cache;\
fastcgi_no_cache $skip_cache;\
fastcgi_cache WORDPRESS;\
add_header X-Cache-Status $upstream_cache_status;' /etc/nginx/sites-enabled/$SITE_URL
else
echo ""
echo "This domain do not exist on this server."
echo ""
exit 1
fi
But if the fastcgi_params
pattern shows up in any other part of the file, and it might at times, it would break everything.
I am guessing that looking for the entire block, which is default and should not change across domains, is a better solution. Just cannot figure out how to do it.
Best Answer
This should work for you.
As mentioned in the above posts... This is not a best-practice solution compared to let's say a configuration manager such as Puppet, Ansible or Salt.
The outcomes of running these operations on a broken
nginx.conf
, would be unpredictable.