📜 ⬆️ ⬇️

Nginx + php-fpm + perl under Debian Squeeze


What is this article for, because there are already many similar ones? In short, when I undertook to set up the bundle I had to reread a huge amount of documentation and various articles, all at once and in one place could not be found. This article attempts to systematize the accumulated knowledge, as well as the most detailed assistance to those who are just beginning to master nginx.

As a test, I decided to transfer all my sites to nginx, before that everything worked on Apache from ZendServerCE. It was interesting to try how difficult it would be to completely move to a new web server, because several CMS are used (DLE, Wordpress, self-written CMS).

Tasks:

')
We have a freshly installed Debian 6 server in a minimal installation from netinstall. And so it went.

1. Preparatory work


Add the necessary further repositories in /etc/apt/sources.list
deb http://backports.debian.org/debian-backports squeeze-backports main contrib non-free deb http://www.deb-multimedia.org stable main non-free deb http://packages.dotdeb.org squeeze all deb-src http://packages.dotdeb.org squeeze all deb http://nginx.org/packages/debian/ squeeze nginx deb-src http://nginx.org/packages/debian/ squeeze nginx 

Install the keys
 apt-get update && apt-get install deb-multimedia-keyring wget http://www.dotdeb.org/dotdeb.gpg -O- |apt-key add - gpg --keyserver hkp://keys.gnupg.net --recv-keys ABF5BD827BD9BF62 gpg -a --export 7BD9BF62 | apt-key add - 

We are updating.
 apt-get update && apt-get upgrade 

From backports we put a fresh core (optional)
 apt-get install -t squeeze-backports linux-image-3.2.0-0.bpo.3-amd64 

Reboot
 reboot 

We put the necessary packages
 apt-get install nginx php5-cli php5-common sqlite php5-sqlite php5-suhosin php5-cgi php5-fpm\ fcgiwrap mysql-server php5-mysql php5-gd php5-apc memcached php5-memcached siege 



Create a directory for sites and logs, also set rights
 mkdir /var/www mkdir /var/log/nginx/ chmod -R a-rwx,u+rwX,g+rX /var/www && chown www-data:www-data -R /var/www #   mkdir /tmp/fcgi-cache/ chown www-data:www-data -R /tmp/fcgi-cache/ 

2. Configure Nginx


Despite the fact that the Nginx configuration consists of several files, nginx itself starts reading a single file: /etc/nginx/nginx.conf, all others are included with the include directive.

Editing /etc/nginx/nginx.conf
 #      nginx user www-data; #      worker_processes 4; pid /var/run/nginx.pid; worker_rlimit_nofile 8192; events { #        worker- worker_connections 1024; #    ,   Linux 2.6+ use epoll; } http { ## #   #   FastCGI ,     ram fastcgi_cache_path /tmp/fcgi-cache/ levels=1:2 keys_zone=one:10m; # sendfile,  ,     , # sendfile   sendfile on; #   #output_buffers 32 512k; #      #  sendfile_max_chunk 128k; #       postpone_output 1460; #    . server_names_hash_bucket_size 64; #   post  client_max_body_size 15m; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; #       nginx server_tokens off; include /etc/nginx/mime.types; default_type application/octet-stream; ## #   access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## #   gzip on; gzip_disable "msie6"; ssi on; ## #    include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } 


Configure a virtual domain

Create directories for domains and templates
 mkdir /etc/nginx/sites-enabled mkdir /etc/nginx/sites-available mkdir /etc/nginx/templates mkdir /var/www/htdocs 


Customize templates.

General pattern
nano / etc / nginx / templates / default
 #       (   ) ## index index.html index.php; #  ""   Drupal (    CMS) location / { try_files $uri $uri/ /index.php?q=$uri&$args; } #     .htaccess  .htpassword location ~ /\.ht { deny all; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } 


Php processing connection template
nano / etc / nginx / templates / php
 #   PHP- PHP-FPM location ~ \.php$ { try_files $uri =404; #PHP-FPM   Unix  fastcgi_pass unix:/tmp/wwwpool.sock; # cache  one fastcgi_cache one; #   ,  3- .        #    fastcgi_cache_min_uses 3; #   fastcgi_cache_valid 200 301 302 304 5m; #   -    nginx    fastcgi_cache_key "$request_method|$host|$request_uri"; #     -             # fastcgi_hide_header "Set-Cookie"; #   nginx       # fastcgi_ignore_headers "Cache-Control" "Expires"; fastcgi_index index.php; # fastcgi_intercept_errors on; #     #    /etc/nginx/fastcgi_param include fastcgi_params; #   ,     php-fpm fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_ignore_client_abort off; } 


Perl Processing Connection Template
nano / etc / nginx / templates / perlcgi
 #    pl  cgi location ~ \.(pl|cgi)$ { #   gzip off; try_files $uri =404; #    fcgiwrap fastcgi_pass unix:/var/run/fcgiwrap.socket; #    include /etc/nginx/fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_ignore_client_abort off; } #  ScriptAlias location /cgi-bin/ { gzip off; try_files $uri =404; root /var/www/; fastcgi_pass unix:/var/run/fcgiwrap.socket; include /etc/nginx/fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_ignore_client_abort off; } 


Phpmyadmin connection template
nano / etc / nginx / templates / phpmyadmin
 location /phpmyadmin { root /var/www/; index index.php index.html index.htm; location ~ ^/phpmyadmin/(.+\.php)$ { try_files $uri =404; root /var/www/; fastcgi_pass unix:/tmp/wwwpool.sock; #fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ { root /var/www/; } } 


Disable the forum.antichat.ru/thread222063-php-fpm.html vulnerability
write in /etc/php5/fpm/php.ini
 cgi.fix_pathinfo=0 


Create a default template for your domain:

nano / etc / nginx / sites-available / default
 server { #     (,     ) root /var/www/htdocs/; #  ,    -   access_log /var/log/nginx/default-access.log; error_log /var/log/nginx/default-error.log; #     ,       . include /etc/nginx/templates/default; include /etc/nginx/templates/php; include /etc/nginx/templates/phpmyadmin; include /etc/nginx/templates/perlcgi; } 


Create a symlink
 ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/000-default 

Remove standard default if there is
  rm /etc/nginx/conf.d/default 

Application of new parameters
 service nginx reload 


If everything is correct, then nginx starts working with the new configuration, if not - work continues with the old, working configuration.

Check php performance.
Create a file test.php in the root directory of the site (in our case it is / var / www / htdocs /) with the following content:
  <?php phpinfo(); ?> 

 chmod 755 /var/www/htdocs/test.php && chown www-data:www-data /var/www/htdocs/test.php 

Then go to the browser IP / test.php , if everything is correct - we get the php parameters on the server, and then delete this file for security.

Perl health check
Create a file test.cgi in the root directory of the site (in our case it is / var / www / htdocs /) with the following content:
 #!/usr/bin/perl -w print "Content-type: text/html\n\n"; print "<html><head><title>Hello World!! </title></head>\n"; print "<body><h1>Hello world</h1></body></html>\n"; 


 chmod 755 /var/www/htdocs/test.cgi && chown www-data:www-data /var/www/htdocs/test.cgi 

Then go to the browser IP / test.cgi , if everything is correct, we get “Hello world”.

If everything works, then at this stage we have a working web server with support for php and perl scripts, then I will describe some of the nuances of setting up individual parts of it.



.htaccess!


In Nginx there is no analogue of Apachev .htaccess, so if the site requires its presence, then you will have to rewrite its content in accordance with the syntax of nginx in the main configuration of the domain. In our config .htaccess has been replaced by the following block:
 location / { try_files $uri $uri/ /index.php?q=$uri&$args; } 

To convert .htaccess to nginx syntax, you can use an online converter, for example

3. Configure PHP-FPM



In Debian, the PHP-FPM configuration consists of 2 parts: global ( /etc/php5/fpm/php-fpm.conf ) and pool settings ( /etc/php5/fpm/pool.d/*.conf ). In this example, we will not touch global settings, but we’ll dwell on setting up pools.

Pula

First, let's look at why we need pools. In case of different requirements of sites to the PHP environment (different php.ini parameters, different number of handlers, etc.), it may be necessary to create additional pools. This operation in PHP-FPM is rather trivial:

The configuration of each pool in Debian is represented by its file in the /etc/php5/fpm/pool.d/ directory. By default, the system has a single pool “www” (file: /etc/php5/fpm/pool.d/www.conf ) and we’ll do it by setting it up.

Workers (handlers)

The most controversial part in setting up a pool is the number of handlers for php scripts. At first glance, it seems that the more handlers, the more efficiently the PHP scripts are processed. But it is not so! Firstly: a large number of processors use more memory (and for our server memory is a very critical resource), secondly: if there are a lot of processors and it so happens that they are all really busy, the server may simply not have enough resources to other tasks (even there is a possibility that SSH connection will become almost impossible).

Ideally, the number of handlers should be such that even with the stress load, the LoadAvarage system remained within reasonable limits. Those. better, under high load, users periodically receive messages about service unavailability (error 502: Gateway timeout) than the complete inaccessibility of the server even for an administrator.

And so a little edit the standard pool nano /etc/php5/fpm/pool.d/www.conf
 #   ,   ,    ,    . ;listen = 127.0.0.1:9000 listen = /tmp/wwwpool.sock #     , .. #    PHP-FPM      pm = dynamic #    . pm.max_children = 7 #   ,     . ..    #     ,     1,      pm.start_servers = 3 #    .       #      pm.start_servers = pm.min_spare_servers. pm.min_spare_servers = 3 #    . ,     pm.max_children #    pm.min_spare_servers.   . pm.max_spare_servers = 4 #       ,          ""  request_slowlog_timeout = 3s #     ""  ( ,    request_slowlog_timeout) slowlog = /var/log/php-slow.log 


The optimal number of handlers depends on server resources, complexity of php scripts, the load created on the mysql server, etc. In any case, the optimal number of handlers must be selected based on the testing of the site. The testing methodology is well described here , I will not repeat.

Adding a pool

If you increase the number of serviced sites, you may need to create additional pools, to configure different parameters for each site - your own. This operation in php-fpm, in our opinion, is rather trivial:
You need to copy the file /etc/php5/fpm/pool.d/www.conf under a new name (for example, let's call it newpool.conf)
Name the new pool: find the line [www] (the name of the first pool) at the top of the new file and change it to [newpool]
We change the address of connection to php-fpm ("listen" directive). Since each address must be unique, then you need to change:
 listen = 127.0.0.1:9000 

on
 listen = 127.0.0.1:9001 

Or, in the case of using unix sockets,
 listen = /tmp/newpool.sock 

Port numbers and paths to unix sockets in all pools must be different!

To apply the settings after changing php.ini (for PHP-FPM, the full path to the file looks like this: /etc/php5/fpm/php.ini ) or your own PHP-FPM settings require a restart of the service.
 service php5-fpm restart 


4. Install phpmyadmin


Download the stable version of phpmyadmin from www.phpmyadmin.net/home_page/downloads.php
 wget http://dl.cihar.com/phpMyAdmin/master/phpMyAdmin-master-latest.tar.gz 

Let's unpack at once to the necessary directory and give the necessary rights.
 tar -xzf phpMyAdmin-master-latest.tar.gz -C /var/www/ mv /var/www/phpMyAdmin-master- /var/www/phpmyadmin chown www-data: /var/www/phpmyadmin -R 

Copy the file with a configuration example and bring it to the following form (generate blowfish_secret here ):
 cp /var/www/phpmyadmin/config.sample.inc.php /var/www/phpmyadmin/config.inc.php nano /var/www/phpmyadmin/config.inc.php 

 $cfg['blowfish_secret'] = 'e%o$fd3}tC9[HxY_$zY+dxstdsZ[i*JG]#GHt]alv' $cfg['Servers'][$i]['auth_type'] = 'http'; $cfg['Servers'][$i]['controluser'] = 'pma'; $cfg['Servers'][$i]['controlpass'] = 'DZMkI4vZ1'; //    $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['tracking'] = 'pma_tracking'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; $cfg['Servers'][$i]['userconfig'] = 'pma_userconfig'; $cfg['SuhosinDisableWarning'] = 'true'; 

Then we create a database and user necessary for phpMyAdmin to work:
 mysqladmin -p create phpmyadmin mysql -p CREATE USER 'pma'@'localhost' IDENTIFIED BY 'DZMkI4vZ1'; GRANT ALL ON phpmyadmin.* TO 'pma'@'localhost'; exit; 

and the necessary for the table using the create_tables.sql script:
 mysql -p phpmyadmin < /var/www/phpmyadmin/examples/create_tables.sql 


Now, when accessing any host in the configuration of which the / etc / nginx / templates / phpmyadmin template is included, we can run phpMyAdmin by going to _http: // hostname / phpmyadmin

When writing materials used:
nginx.org/ru/docs
habrahabr.ru/post/65128
manualpages.pro/node/31
dklab.ru/chicken/nablas/56.html
linuxwork.org.ua/debian/ustanovka-oficialnoj-versii-phpmyadmin-s-vozmozhnostyu-obnovleniya-na-debian-6-0-squeeze
www.hilik.org.ua/tuning-nginx

Source: https://habr.com/ru/post/164401/


All Articles