Centos installation and configuration lnmp

Source: Internet
Author: User
Tags sendfile website server 403 forbidden error account gmail

PDF Document Download: http://www.coderblog.cn/doc/Install_and_config_LNMP_under_CentOS.pdf

EPUB Document Download: http://www.coderblog.cn/doc/Install_and_config_LNMP_under_CentOS.epub

Link: http://www.coderblog.cn/article/36/

Centos installation and configuration lnmp (1): nginx installation and Common commands

Nginx is a lightweight HTTP server. Compared with Apache, nginx has the following advantages. In terms of performance, it uses a small amount of system resources and supports more concurrent connections, nginx is an excellent proxy server and Server Load balancer server. nginx is easy to install and flexible to configure. Centos is the most common Linux System for website servers. This article describes how to install and configure nginx in a pure system after purchasing a VPs host or cloud host.

I. installation environment
  • Operating System: centos
  • Install software: nginx 1.6.0
  • Installation Method: Yum
  • Installation instructions: Unless otherwise specified, perform the following operations:
Ii. Installation

Generally, the yum software source of centos does not contain nginx software. Therefore, we need to import additional Yum software sources.

rpm -ivh http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm

yum install nginx

List of installed files

  • Self-starting script file:/etc/init.d/nginx
  • Main program file:/usr/sbin/nginx
  • Configuration file directory:/etc/nginx/
  • Main configuration file:/etc/nginx/nginx.conf
  • Configuration files for each site/etc/nginx/conf.d/*.conf
  • Log File directory:/var/log/nginx/
  • Access log:/var/log/nginx/access.log
  • Error Log:/var/log/nginx/error.log
3. Program startup

/etc/init.d/nginx start

Or

/etc/init.d/nginx restart

If you see the following results, the nginx program has been successfully started.

Starting nginx: [ OK ]

4. View websites

Generally, website servers do not provide graphical interfaces. Therefore, you must obtain the IP address of the website server by remotely viewing the website on the server.

ifconfig

Then we can enter http: // server IP Address/in the browser to view our website. If you see the following results, congratulations, your website can be accessed normally.

5. Common nginx commands
  • View nginx version:nginx -v
  • Test whether the configuration file is correct:nginx -t
  • Test whether the specified configuration file is correct:nginx -t -c *filepath*
  • Start/stop/restart

/etc/init.d/nginx start

/etc/init.d/nginx stop

/etc/init.d/nginx restart

  • After modifying the configuration file, do not start re-loading the Configuration:nginx -s reload
Vi. troubleshooting

If your website cannot be accessed normally, follow these steps:

1. Check whether port 80 has been used by nginx.

netstat -tlunpOrnetstat -tlunp|grep :80

If the following content exists, the nginx program has listened to port 80 normally.

tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 573/nginx

2. Check whether the website can be accessed locally

curl http://localhost/If the HTML code of the nginx welcome page is returned, it is normal.

3. Port 80 is blocked by the system for external access

Method 1: Disable the iptables service

iptables stop

chkconfig iptables off

Method 2: enable external access on port 80

/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT

/etc/init.d/iptables save

4. View Error Log Files

more /var/log/nginx/error.log

Centos installation and configuration lnmp (2): nginx Optimization

After installing nginx in a simple way, you need to configure it, such as configuring the file path of the website, sharing the same port for multiple websites, combining it with PHP, and optimizing it.

1. Main configuration file

Nginx main configuration file path:/etc/nginx/nginx.conf

user  nginx;worker_processes  1;error_log  /var/log/nginx/error.log warn;pid        /var/run/nginx.pid;events {    worker_connections  1024;}http {    include       /etc/nginx/mime.types;    default_type  application/octet-stream;    log_format  main  ‘$remote_addr - $remote_user [$time_local] "$request" ‘                      ‘$status $body_bytes_sent "$http_referer" ‘                      ‘"$http_user_agent" "$http_x_forwarded_for"‘;    access_log  /var/log/nginx/access.log  main;    sendfile        on;    #tcp_nopush     on;    keepalive_timeout  65;    #gzip  on;    include /etc/nginx/conf.d/*.conf;}
  • user nginx;Users running nginx programs
  • worker_processes 1;Number of worker processes. We recommend that you change it to the same number as the number of CPU cores, for example, 4-core CPU.
  • error_log /var/log/nginx/error.log warn;File Path and log type of error logs
  • pid /var/run/nginx.pid;The file that stores the nginx process number. You can use this file to send information to nginx in the future, such as kill-HUP 'cat/var/run/nginx. Pi'
  • worker_connections 1024;The number of concurrent jobs supported by worker. A server that supports high concurrency can be modified to 65536. This modification must be used with the Linux kernel to take effect;
  • include /etc/nginx/mime.types;Sets the MIME type, which is defined by the mime. type file.
  • Define the log format. The format name command is main:
 
Log_format main '$ remote_addr-$ remote_user [$ time_local] "$ request" ''$ Status $ response" $ http_referer "'' "$ http_user_agent" "$ http_x_forwarded_for "'; the meaning of each field is as follows: $ remote_addr and $ http_x_forwarded_for are used to record the Client IP address; $ remote_user: used to record the client user name; $ time_local: used to record the access time and time zone; $ request: used to record the request URL and HTTP protocol; $ status: used to record the Request status; success is 200, $ body_bytes_sent: record the size of the content sent to the client file body; $ http_referer: used to record access from the page Link; $ http_user_agent: record information about the client browser;
  • access_log /var/log/nginx/access.log main;Log File Path. Main is the log format name just defined.
  • sendfile on;The sendfile command specifies whether nginx calls the sendfile function (zero copy mode) to output files. For common applications, it must be set to on. If it is used for application disk I/O heavy load applications such as downloading, you can set it to off to balance the disk and network I/O processing speed and reduce the system uptime.
  • keepalive_timeout 65;Keepalive timeout
  • include /etc/nginx/conf.d/*.conf;This statement contains the. conf file in the/etc/nginx/CONF. d/directory as the configuration file.
Ii. Some additional settings of the main configuration file 1. Open Gzip

Generally, server configurations are powerful and network bandwidth is relatively small. The gzip function is used to compress the webpage content within the sending webpage. The client browser receives the file name and decompress it, this can save a lot of network bandwidth. Add the following options to the main configuration file:

Gzip on; # Open gzipgzip_min_length 1 K; # Content smaller than 1 kb will not be compressed, because the larger the pressure, gzip_buffers 4 16 K; # gzip cache settings the system obtains 4 16 KB caches for storing gzip compressed result data streams # gzip_http_version 1.0; gzip_comp_level 2; # compression level gzip_types text/plain application/X-JavaScript text/CSS application/XML text/JavaScript Application/X-httpd-PHP; # mime typegzip_vary off to be compressed; gzip_disable "MSIE [1-6] \. "; # Do not compress browsers under IE6
2. Increase the file upload size

By default, the size of files that can be uploaded by nginx is only 1 MB, which far cannot meet our needs. Therefore, you can add the following options to increase the size of uploaded files.

client_max_body_size 10m;

3. Website configuration file path

The configuration files of nginx websites are stored in/etc/nginx/conf.d/Directory, each. conf file represents each independent website. Let's look at the structure of a classic CONF file, that is/etc/nginx/conf.d/default.confFile:

server {    listen       80;    server_name  localhost;    #charset koi8-r;    #access_log  /var/log/nginx/log/host.access.log  main;    location / {        root   /usr/share/nginx/html;        index  index.html index.htm;    }    #error_page  404              /404.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           html;    #    fastcgi_pass   127.0.0.1:9000;    #    fastcgi_index  index.php;    #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;    #}}

Let's explain it separately.

  • All configurations must be included inserver{}Medium
  • listen 80 ;Listen to port 80
  • server_name localhost;The website name is separated from other websites. Here, you should modify the domain name for your application. Separate multiple websites with spaces, for example:server_name www.coderblog.cn coderblog.cn;In addition, the URL here can also be in the form of a regular expression, suchserver_name (www\.)?coderblog.cn;
  • charset koi8-r;File encoding, which is generally setcharset utf-8;
  • access_log /var/log/nginx/log/host.access.log main;The file path of the access log and the log type to be recorded. Main is the log format defined by nginx. conf.

  • Website file storage path and default document name, suchhttp://www.coderblog.cn/, Actually accesshttp://www.coderblog.cn/index.htm
 
location / {    root   /usr/share/nginx/html;    index  index.html index.htm;}
  • error_page 404 /404.html;When the file is not found, it is relocated to the/404.html file.

  • When a 500 502 503 504 error occurs, move to the/50x.html file.
 
error_page   500 502 503 504  /50x.html;location = /50x.html {   root   /usr/share/nginx/html;}
  • Disable access to some files
 
location ~ /\.ht {    deny  all;}
Iv. Possible errors after Configuration Modification

After the configuration file is modifiednginx -tVerify the configuration file and usenginx -s reloadReload the configuration file.

1. A 403 Forbidden error occurs during access after the file path is modified.

Possible cause 1: missing document files, such as missing index.html index.htm and any default file in the rootdirectory. When you directly access the website domain name, the 403 Forbidden error will occur. solution: add at least one default document to the root directory

Possible cause 2: The nginx user does not have the read permission under the root directory. For example, set the root directory to/home/homeway, and the permission for this directory isdrwx------That is, other users except homeway users do not have the read and write permissions. Solution: Change the root directory permission to 777, that is, anyone can read, write, and execute commands.chmod 777 /home/homeway -RYou can.

5. Multiple websites share port 80

Nginx is easy to implement multi-site sharing of port 80. You only need to set the SERVER_NAME attribute. For example, if I have two websites: forum.coderblog.cn and blog.coderblog.cn, then I only need to go to/etc/nginx/CONF. d/Add two files/etc/nginx/conf.d/forum.coderblog.cn.conf

listen       80;server_name  forum.coderblog.cn;

/etc/nginx/conf.d/blog.coderblog.cn.conf

listen       80;server_name  blog.coderblog.cn;

Now, this article will talk about nginx and PHP in the next article.

Centos installation and configuration lnmp (3): nginx and PHP

PHP can be said to be the most popular preferred language for websites. The previous two articles have explained how to set up and optimize the nginx environment in the centos environment. This article describes how to install PHP in centos, combined with spawn-fcgi and nginx.

1. install PHP in centos

So far, the latest version of PHP is 5.6.0. However, in the actual production environment, PHP 5.3.3 can meet the needs of most programs. It runs stably and has many extension modules, therefore, we recommend that you install PHP 5.3.3.

  • Operating System: centos
  • Install software: PhP 5.3.3
  • Installation Method: Yum
  • Installation instructions: Unless otherwise specified, perform the following operations:
Ii. Installation

rpm -Uvh http://repo.webtatic.com/yum/el6/latest.rpm

yum install php php-mysql php-gd php-gd php-mcrypt php-xml php-xcache php-mbstring

List of installed files

  • Configuration File/etc/php.ini
  • Program file/usr/bin/php-cgi, Usephp-cgi -b portTo listen to a port, but it is generally not recommended to run this method
3. Use spawn-fcgi to manage PHP Processes

Spawn-fcgi is a component in lightpd that can be used independently. Use the following command to install

wget http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2tar -xvjf lighttpd-1.4.18.tar.bz2cd lighttpd-1.4.18./configuremakemake install

Common commands:

spawn-fcgi -C 5 -u nginx -g nginx -f /usr/bin/php-cgi -a 127.0.0.1 -p 9000

Parameter description:

  • -C 5Start five PHP processes for processing
  • -u nginx -g nginxRun PHP with nginx of the user and nginx of the user group
  • -f /usr/bin/php-cgiSpecify the file path of PHP-CGI
  • -a 127.0.0.1 -p 9000Listener IP address and port

After running, usenetstat -tlunpThe following information is displayed:

Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      13320/php-cgi 

If you usekill -9 pidIn the form of, spawn-fcgi will think that the process has crashed and another process will be started immediately. Therefore, it is necessary to execute the kill command multiple times-C 5The specified number of processes is related, so we recommend that you usepkill php-cgiTo kill all PHP-CGI processes at one time.

4. Configure the nginx configuration file

To combine PHP with nginx, you need to add the statement for processing the file ending with. php In the website configuration file. For example:

location ~\.php$ {    root   /home/homeway/coder;    index  index.html index.htm;    fastcgi_index index.php;    fastcgi_pass  127.0.0.1:9000;    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;    fastcgi_param  QUERY_STRING       $query_string;    fastcgi_param  REDIRECT_STATUS    200;    include       fastcgi_params;}

Main configuration explanation:

  • location ~\.php$Match All files ending with. php for processing.
  • fastcgi_index index.php;Homepage File
  • fastcgi_pass 127.0.0.1:9000;Pass the file to the program listening to the port for processing, that is, our PHP-CGI program
  • include fastcgi_params;The parameter configuration file must be modified in two ways.

In/etc/nginx/fastcgi_paramsAdd the following information to the file (skip this step if it already exists)

# PHP only, required if PHP was built with --enable-force-cgi-redirectfastcgi_param  REDIRECT_STATUS    200;fastcgi_param  PATH_INFO          "";fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
V. Test Run

Add the test. php file under the root path of the website. The content is as follows:

<?php echo phpinfo();?>

Access the file. If php information appears, it indicates that PHP has been successfully run.

Centos installation and configuration lnmp (4): MySQL database

MySQL database is one of the most popular relational databases. Its functions and performance are sufficient to meet the needs of most small and medium-sized enterprises. Therefore, MySQL database is the first choice in database selection. This article describes how to install MySQL Databases in centos. Although it is not necessarily related to nginx, It is a supplement to the nginx series, we hope to build a complete centos website runtime environment.

I. installation environment
  • Operating System: centos
  • Install software: MySQL 5.1.73
  • Installation Method: Yum
  • Installation instructions: Unless otherwise specified, perform the following operations:
Ii. Installation

yum install mysql mysql-server

List of installed files

  • /etc/my.cnfConfiguration File
  • /usr/bin/mysqlClient program on the text interface
  • /etc/init.d/mysqldMySQL Service Startup Script
  • /usr/bin/mysqladminProcedures for managing and configuring MySQL
Iii. Common commands to start the MySQL Service

/etc/init.d/mysqld startOrservice mysqld start

Set to boot

chkconfig mysqld on

Change Password

After the initial installation, the initial password is blank. For website security, you need to modify the password. The command is as follows,

mysqladmin -uroot -p password coderblog

In this case, you are required to enter the original password, but because the initial password is empty, press enter directly.

The command is interpreted as follows:

  • -u root -pEnter the password to log on as the root user.
  • password coderblogChange Password to coderblog
Login

Mysql-u user-P Password

Back up and restore a database

Mysqldump-u user-P Password Database Name> file path

For example:

mysqldump -uroot -pcoder coder > /home/homeway/coder.sql

Restore database

Go to the MySQL command interface and perform reduction:

mysql -uroot -pcoder> create database coder;> source /home/homeway/coder.sql;> exit

Direct Reduction:Mysql-u user-P Password Database Name-e 'source file Path'

-eIs to execute the command, directly end the program after execution

mysql -uroot -pcoder coder -e ‘source /home/homeway/coder.sql‘

Simple Configuration Optimization

In/etc/my.cnfAdd the following content

default-character-set=utf8key_buffer_size = 256Mmax_allowed_packet = 4Mthread_stack = 256Ktable_cache = 128Ksort_buffer_size = 6Mread_buffer_size = 4Mjoin_buffer_size = 8Mmyisam_sort_buffer_size = 64Mtable_cache = 512thread_cache_size = 64query_cache_size = 64Mtmp_table_size = 256Mmax_connections = 2048wait_timeout = 60thread_concurrency = 8
Centos installation and configuration lnmp (5): Use goaccess to analyze nginx logs and send email reports

Goaccess is a log analysis software with excellent performance. It is very suitable for analyzing logs generated by nginx and can form HTML reports. It uses crontab to schedule tasks, analyze logs on the host every day and send a report to the O & M personnel's mailbox, so that you can understand the running status of the website.

1. Install software
  • Log Analysis Software goaccess:yum install goaccess
  • Email sending software mutt:yum install mutt
  • SMTP software msmtp:yum install msmtp
Ii. daily use

Use commandsGoaccess-F Log File PathTo analyze a log file. At the first startup, a dialog box is displayed asking about the log file format, as shown in:

Select the third, that isNCSA Commbined Log Format, Use the space key to select, then press enter to confirm, and then goaccess will quickly analyze the complete log file.

If you do not want to select the log file format every time, you can create a new configuration file, such~/.garc, The content is as follows:

color_scheme 1date_format %d/%b/%Ylog_format %h %^[%d:%^] "%r" %s %b "%R" "%u"

Then, when you start the program, specify the path of the configuration file:

Goaccess-P ~ /. Garc-F Log File Path

3. Test the mail sending function 1. Set the mail sending account

Edit msmtp configuration file~/.msmtprc

Defaultsaccount gmailtls onauth onhost SMTP. Gmail. comport 587 user mailbox name from mailbox name password mailbox password tls_starttls ontls_trust_file/etc/pki/tls/certs/ca-bundle.crtaccount default: Gmail

The preceding example uses Gmail as an example. You can use your own email address to set it.account gmailIngmailAccount ID, last lineaccount default: gmailSpecify the default accountgmail, Use the default account to send the email when mutt sends the email.

You can also use other mailboxes. Some options for different mailboxes are not the same. If you use QQ mailbox, You need to disable tls_starttls. The following is an example of a QQ mailbox:

Defaultsaccount qqtls onauth onhost SMTP. QQ. comport 465 user homeway88from [email protected] Password tls_starttls offtls_trust_file/etc/pki/tls/certs/ca-bundle.crtaccount default: QQ
2. Configure mutt to use msmtp to send mail instead of Sendmail

By default, Mutt uses Sendmail to send emails. If your host does not have the post office function, the emails are sent only to the account mailbox of the local host, however, we generally need to use the external SMTP service to send emails to Internet mailboxes.

Edit the mutt configuration file/etc/Muttrc.LocalAdd the following content. Note that the sender's email address must be consistent with the sender's email address of the specified msmtp.

Set Sendmail = "/usr/bin/msmtp" set from = "sender mail" set Sendmail = "/usr/local/msmtp/bin/msmtp" set use_from = Yes set realname = "sender"
3. Use mutt to send the test email

The common mail sending command of mutt is

Echo "email content" | mutt-s "email title"-A attachment file path-c recipient email

4. regularly generate log reports and send emails

Break down tasks

  • Timed crontab
  • Generate a log report goaccess
  • Send email mutt

The scheduled task format is:

Hour, day, month, and week commands

If we want to generate a log report at every night, usecrontab -eAnd then add the following content.

59 23 * * * sh /home/homeway/report/nginx.sh

Then create/home/homeway/report/nginx.sh, Enter the following content

DATE=$(date +%Y%m%d)mkdir /home/homeway/report/$DATEcd /home/homeway/report/$DATEcp /home/homeway/log/access.log .echo "" > /home/homeway/log/access.logcat *.log > all.loggoaccess -f /home/report/$DATE/all.log -a -p ~/.garc > report.htmlecho "$DATE Report" | mutt -s "$DATE Report" -a /home/homeway/report/$DATE/report.html -c [email protected]

The command is interpreted as follows:

  • DATE=$(date +%Y%m%d)Obtain the current date, in the format of year, month, day, such as 20140101
  • Create an archive folder for this datemkdir /home/homeway/report/$DATE, And copy the log file to this folder and clear the original log file, usecat *.log > all.logBecause there are usually multiple files on the host, you need to combine multiple log files into one.
  • goaccess -f /home/report/$DATE/all.log -a -p ~/.garc > report.htmlAnalyticdb outputs the result to the report.html file.
  • echo "$DATE Report" | mutt -s "$DATE Report" -a /home/homeway/report/$DATE/report.html -c [email protected]To send the report file as an attachment[email protected]Email.
V. Conclusion

So far, this series of articles has come to an end, while writing articles to improve the blog, although it has taken a lot of time, but it is also very rewarding, you can make a look at the skills learned, in order to avoid forgetting it after a long time, I also hope to help later users.

Due to my limited energy, the article will inevitably have mistakes and shortcomings. I hope you will not give me any further advice.

 

Article: centos installation and configuration lnmp

Homeway88

Published in: Cheng xuape blog Co., http://www.coderblog.cn/

Link: http://www.coderblog.cn/article/36/

Reprinted please indicate the source

Centos installation and configuration lnmp

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.