centos5.3搭建安全高效的LNMP服务器

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:
操作系统基于centos 5.3
#!/bin/bash
# BY kerryhu
# QQ:263205768
# MAIL:king_819@163.com
# BLOG:http://kerry.blog.51cto.com
# Please manual operation yum of before Operation.....
# yum install ntp vim-enhanced gcc gcc-c++ flex bison autoconf \
# automake bzip2-devel ncurses-devel libjpeg-devel libpng-devel \
# libtiff-devel freetype-devel pam-devel kernel netconfig
#============================更新系统时间===========================================
yum install ntp
ntpdate time.nist.gov
crontab -e 
00 01 * * * /usr/sbin/ntpdate time.nist.gov
#============================安装开源组件===========================================
sudo -s
LANG=C
yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers
#============================下载安装包=============================================
cd /opt
wget 
http://sysoev.ru/nginx/nginx-0.8.34.tar.gz
wget  http://www.php.net/get/php-5.2.13.tar.gz/from/this/mirror
wget  http://php-fpm.org/downloads/php-5.2.13-fpm-0.5.13.diff.gz
wget  http://mirrors.sohu.com/mysql/MySQL-5.5/mysql-5.5.2-m2.tar.gz
wget  http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.tar.gz
wget " http://downloads.sourceforge.net/mcrypt/libmcrypt-2.5.8.tar.gz?modtime=1171868460&big_mirror=0 "
wget "
http://downloads.sourceforge.net/mcrypt/mcrypt-2.6.8.tar.gz?modtime=1194463373&big_mirror=0 "
wget 
http://pecl.php.net/get/memcache-2.2.5.tgz
wget " http://downloads.sourceforge.net/mhash/mhash-0.9.9.9.tar.gz?modtime=1175740843&big_mirror=0 "
wget 
ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.01.tar.gz
wget  http://bart.eaccelerator.net/source/0.9.6/eaccelerator-0.9.6.tar.bz2
wget  http://pecl.php.net/get/PDO_MYSQL-1.0.2.tgz
wget  http://blog.s135.com/soft/linux/nginx_php/imagick/ImageMagick.tar.gz
wget  http://pecl.php.net/get/imagick-2.3.0.tgz
#============================编译安装php所需的支持库=================================
cd /opt
tar zxvf libiconv-1.13.tar.gz
cd libiconv-1.13/
./configure --prefix=/usr/local
make;make install
cd ../
tar zxvf libmcrypt-2.5.8.tar.gz 
cd libmcrypt-2.5.8/
./configure
make;make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make;make install
cd ../../
tar zxvf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9/
./configure
make;make install
cd ../
ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
tar zxvf mcrypt-2.6.8.tar.gz
cd mcrypt-2.6.8/
/sbin/ldconfig
./configure
make;make install
cd ../
#=============================编译安装MySQL 5.5.2-m2=========================
cd /opt
mkdir -p /usr/local/mysql
useradd mysql -d /usr/local/mysql -s /sbin/nologin
tar zxvf mysql-5.5.2-m2.tar.gz
cd mysql-5.5.2-m2/
./configure --prefix=/usr/local/mysql/ --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-tables --with-readline --with-ssl --with-embedded-server --enable-local-infile --with-plugins=partition,innobase,myisammrg
make;make install
chown -R mysql:mysql /usr/local/mysql/
mkdir -p /data/mysql/data
mkdir -p /data/mysql/binlog
mkdir -p /data/mysql/relaylog
mkdir -p /data/mysql/mysql
chown -R mysql:mysql /data/mysql
/usr/local/mysql/bin/mysql_install_db --basedir=/usr/local/mysql --datadir=/data/mysql/data --user=mysql
#编辑mysql配置文件
vi /data/mysql/my.cnf
[client]
character-set-server = utf8
port    = 3306
socket  = /tmp/mysql.sock
[mysqld]
character-set-server = utf8
replicate-ignore-db = mysql
replicate-ignore-db = test
replicate-ignore-db = information_schema
user    = mysql
port    = 3306
socket  = /tmp/mysql.sock
basedir = /usr/local/mysql
datadir = /data/mysql/data
log-error = /data/mysql/mysql_error.log
pid-file = /data/mysql/mysql.pid
open_files_limit    = 10240
back_log = 600
max_connections = 5000
max_connect_errors = 6000
table_cache = 614
external-locking = FALSE
max_allowed_packet = 32M
sort_buffer_size = 1M
join_buffer_size = 1M
thread_cache_size = 300
thread_concurrency = 8
query_cache_size = 512M
query_cache_limit = 2M
query_cache_min_res_unit = 2k
default-storage-engine = MyISAM
thread_stack = 192K
transaction_isolation = READ-COMMITTED
tmp_table_size = 246M
max_heap_table_size = 246M
long_query_time = 3
log-slave-updates
log-bin = /data/mysql/binlog/binlog
binlog_cache_size = 4M
binlog_format = MIXED
max_binlog_cache_size = 8M
max_binlog_size = 100M
relay-log-index = /data/mysql/relaylog/relaylog
relay-log-info-file = /data/mysql/relaylog/relaylog
relay-log = /data/mysql/relaylog/relaylog
expire_logs_days = 30
key_buffer_size = 256M
read_buffer_size = 1M
read_rnd_buffer_size = 16M
bulk_insert_buffer_size = 64M
myisam_sort_buffer_size = 128M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
myisam_recover
interactive_timeout = 120
wait_timeout = 120
skip-name-resolve
master-connect-retry = 10
slave-skip-errors = 1032,1062,126,1114,1146,1048,1396
#master-host     =   192.168.1.2
#master-user     =   username
#master-password =   password
#master-port     =  3306
server-id = 1
innodb_additional_mem_pool_size = 16M
innodb_buffer_pool_size = 512M
innodb_data_file_path = ibdata1:256M:autoextend
innodb_file_io_threads = 4
innodb_thread_concurrency = 8
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 16M
innodb_log_file_size = 128M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
innodb_file_per_table = 0
#log-slow-queries = /data/mysql/slow.log
#long_query_time = 10
[mysqldump]
quick
max_allowed_packet = 32M
#设置mysql启动文件
cp support-files/mysql.server /etc/rc.d/init.d/mysqld 
sed -i 's#basedir=#basedir=/usr/local/mysql#' /data/mysql/my.cnf
sed -i 's#datadir=#datadir=/data/mysql/data#' /data/mysql/my.cnf   
chmod 700 /etc/rc.d/init.d/mysqld
/etc/rc.d/init.d/mysqld start
chkconfig --add mysqld 
chkconfig --level 2345 mysqld on
ln -s /usr/local/mysql/bin/mysql /sbin/mysql 
ln -s /usr/local/mysql/bin/mysqladmin /sbin/mysqladmin
#设置root密码(1q2w3e)
mysqladmin -u root password 1q2w3e
#配置库文件搜索路径
echo "/usr/local/mysql/lib/mysql" >> /etc/ld.so.conf
ldconfig
#添加/usr/local/mysql/bin到环境变量PATH中
export PATH=$PATH:/usr/local/mysql/bin
#添加mysql管理帐户
mysql -h localhost -u root -p1q2w3e
msqyl> use mysql;
msqyl> grant all on *.* to 
'kerry'@'172.16.16.150'  identified by 'kerry1q2w3e';
msqyl> flush privileges; 
msqyl> exit;

#==========================编译安装PHP(FastCGI模式)===============================
#编译安装php-5.2.13
cd /opt
tar zxvf php-5.2.13.tar.gz
gzip -cd php-5.2.13-fpm-0.5.13.diff.gz | patch -d php-5.2.13 -p1
cd php-5.2.13/
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-fpm --enable-force-cgi-redirect --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap
make ZEND_EXTRA_LIBS='-liconv'
make install
cp php.ini-dist /usr/local/php/etc/php.ini
cd ../
#编译安装PHP5扩展模块
tar zxvf memcache-2.2.5.tgz
cd memcache-2.2.5/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make;make install
cd ../
tar jxvf eaccelerator-0.9.6.tar.bz2
cd eaccelerator-0.9.6/
/usr/local/php/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/php/bin/php-config
make;make install
cd ../
tar zxvf PDO_MYSQL-1.0.2.tgz
cd PDO_MYSQL-1.0.2/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-pdo-mysql=/usr/local/mysql
make;make install
cd ../
tar zxvf ImageMagick.tar.gz
cd ImageMagick-6.5.1-2/
./configure
make;make install
cd ../
tar zxvf imagick-2.3.0.tgz
cd imagick-2.3.0/
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make;make install
cd ../

#手动修改php.ini文件
    手工修改:查找/usr/local/php/etc/php.ini中的extension_dir = "./"
修改为extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"
并在此行后增加以下几行,然后保存:
extension = "memcache.so"
extension = "pdo_mysql.so"
extension = "imagick.so"
  再查找output_buffering = Off
修改为output_buffering = On
#自动修改php.ini文件
sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"\nextension = "memcache.so"\nextension = "pdo_mysql.so"\nextension = "imagick.so"\n#' /usr/local/php/etc/php.ini
sed -i 's#output_buffering = Off#output_buffering = On#' /usr/local/php/etc/php.ini
sed -i "s#; always_populate_raw_post_data = On#always_populate_raw_post_data = On#g" /usr/local/php/etc/php.ini
#配置eAccelerator加速PHP:
mkdir -p /usr/local/eaccelerator_cache
vi /usr/local/php/etc/php.ini
[eaccelerator]
zend_extension="/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/usr/local/eaccelerator_cache"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="3600"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
#创建www用户和组,以及供blog.56diy.com和 www.56diy.com 两个虚拟主机使用的目录:
groupadd www
useradd -g www -s /sbin/nologin www
mkdir -p /data/www/blog.56diy.com
chmod +w /data/www/blog.56diy.com
chown -R www:www /data/www/blog.56diy.com
mkdir -p /data/www/www.56diy.com
chmod +w /data/www/www.56diy.com
chown -R www:www /data/www/www.56diy.com
#创建php-fpm配置文件(php-fpm是为PHP打的一个FastCGI管理补丁,可以平滑变更php.ini配置而无需重启php-cgi):
mv /usr/local/php/etc/php-fpm.conf /usr/local/php/etc/php-fpm.conf.bak
vi /usr/local/php/etc/php-fpm.conf
#//输入以下内容(如果您安装 Nginx + PHP 用于程序调试,请将以下的<value name="display_errors">0</value>改为<value name="display_errors">1</value>,以便显示PHP错误信息,否则,Nginx 会报状态为500的空白错误页):
<?xml version="1.0" ?>
<configuration>
  All relative paths in this config are relative to php's install prefix
  <section name="global_options">
    Pid file
    <value name="pid_file">/usr/local/php/logs/php-fpm.pid</value>
    Error log file
    <value name="error_log">/usr/local/php/logs/php-fpm.log</value>
    Log level
    <value name="log_level">notice</value>
    When this amount of php processes exited with SIGSEGV or SIGBUS ...
    <value name="emergency_restart_threshold">10</value>
    ... in a less than this interval of time, a graceful restart will be initiated.
    Useful to work around accidental curruptions in accelerator's shared memory.
    <value name="emergency_restart_interval">1m</value>
    Time limit on waiting child's reaction on signals from master
    <value name="process_control_timeout">5s</value>
    Set to 'no' to debug fpm
    <value name="daemonize">yes</value>
  </section>
  <workers>
    <section name="pool">
      Name of pool. Used in logs and stats.
      <value name="name">default</value>
      Address to accept fastcgi requests on.
      Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket'
      <value name="listen_address">127.0.0.1:9000</value>
      <value name="listen_options">
        Set listen(2) backlog
        <value name="backlog">-1</value>
        Set permissions for unix socket, if one used.
        In Linux read/write permissions must be set in order to allow connections from web server.
        Many BSD-derrived systems allow connections regardless of permissions.
        <value name="owner"></value>
        <value name="group"></value>
        <value name="mode">0666</value>
      </value>
      Additional php.ini defines, specific to this pool of workers.
      <value name="php_defines">
        <value name="sendmail_path">/usr/sbin/sendmail -t -i</value>
        <value name="display_errors">0</value>
      </value>
      Unix user of processes
      <value name="user">www</value>
      Unix group of processes
      <value name="group">www</value>
      Process manager settings
      <value name="pm">
        Sets style of controling worker process count.
        Valid values are 'static' and 'apache-like'
        <value name="style">static</value>
        Sets the limit on the number of simultaneous requests that will be served.
        Equivalent to Apache MaxClients directive.
        Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi
        Used with any pm_style.
        <value name="max_children">128</value>
        Settings group for 'apache-like' pm style
        <value name="apache_like">
          Sets the number of server processes created on startup.
          Used only when 'apache-like' pm_style is selected
          <value name="StartServers">20</value>
          Sets the desired minimum number of idle server processes.
          Used only when 'apache-like' pm_style is selected
          <value name="MinSpareServers">5</value>
          Sets the desired maximum number of idle server processes.
          Used only when 'apache-like' pm_style is selected
          <value name="MaxSpareServers">35</value>
        </value>
      </value>
      The timeout (in seconds) for serving a single request after which the worker process will be terminated
      Should be used when 'max_execution_time' ini option does not stop script execution for some reason
      '0s' means 'off'
      <value name="request_terminate_timeout">0s</value>
      The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file
      '0s' means 'off'
      <value name="request_slowlog_timeout">0s</value>
      The log file for slow requests
      <value name="slowlog">logs/slow.log</value>
      Set open file desc rlimit
      <value name="rlimit_files">65535</value>
      Set max core size rlimit
      <value name="rlimit_core">0</value>
      Chroot to this directory at the start, absolute path
      <value name="chroot"></value>
      Chdir to this directory at the start, absolute path
      <value name="chdir"></value>
      Redirect workers' stdout and stderr into main error log.
      If not set, they will be redirected to /dev/null, according to FastCGI specs
      <value name="catch_workers_output">yes</value>
      How much requests each process should execute before respawn.
      Useful to work around memory leaks in 3rd party libraries.
      For endless request processing please specify 0
      Equivalent to PHP_FCGI_MAX_REQUESTS
      <value name="max_requests">1024</value>
      Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.
      Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+)
      Makes sense only with AF_INET listening socket.
      <value name="allowed_clients">127.0.0.1</value>
      Pass environment variables like LD_LIBRARY_PATH
      All $VARIABLEs are taken from current environment
      <value name="environment">
        <value name="HOSTNAME">$HOSTNAME</value>
        <value name="PATH">/usr/local/bin:/usr/bin:/bin</value>
        <value name="TMP">/tmp</value>
        <value name="TMPDIR">/tmp</value>
        <value name="TEMP">/tmp</value>
        <value name="OSTYPE">$OSTYPE</value>
        <value name="MACHTYPE">$MACHTYPE</value>
        <value name="MALLOC_CHECK_">2</value>
      </value>
    </section>
  </workers>
</configuration>
#启动php-cgi进程,监听127.0.0.1的9000端口,<value name="max_children">128</value>进程数为128(如果服务器内存小于3GB,可以只开启64个进程),用户为www:
ulimit -SHn 65535
/usr/local/php/sbin/php-fpm start
#//注:/usr/local/php/sbin/php-fpm还有其他参数,包括:start|stop|quit|restart|reload|logrotate,修改php.ini后不重启php-cgi,重新加载配置文件使用reload。
#==================================安装Nginx 0.8.34 =========================================
#安装Nginx所需的pcre库:
cd /opt
tar zxvf pcre-8.01.tar.gz
cd pcre-8.01/
./configure
make;make install
cd ../
#安装Nginx
tar zxvf nginx-0.8.34.tar.gz
cd nginx-0.8.34/
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make;make install
cd ../

#创建Nginx日志目录
mkdir -p /data/logs/blog.56diy.com
chmod +w /data/logs/blog.56diy.com
chown -R www:www /data/logs/blog.56diy.com
mkdir -p /data/logs/www.56diy.com
chmod +w /data/logs/www.56diy.com
chown -R www:www /data/logs/www.56diy.com
#创建Nginx配置文件
mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak
vi /usr/local/nginx/conf/nginx.conf
user  www www;
worker_processes 8;
error_log  /data/logs/nginx_error.log  crit;
pid        /usr/local/nginx/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process. 
worker_rlimit_nofile 65535;
events 
{
  use epoll;
  worker_connections 65535;
}
http 
{
  include       mime.types;
  default_type  application/octet-stream;
  #charset  gb2312;
      
  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 8m;
      
  sendfile on;
  tcp_nopush     on;
  keepalive_timeout 60;
  tcp_nodelay on;
  fastcgi_connect_timeout 300;
  fastcgi_send_timeout 300;
  fastcgi_read_timeout 300;
  fastcgi_buffer_size 64k;
  fastcgi_buffers 4 64k;
  fastcgi_busy_buffers_size 128k;
  fastcgi_temp_file_write_size 128k;
  gzip on;
  gzip_min_length  1k;
  gzip_buffers     4 16k;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_types       text/plain application/x-javascript text/css application/xml;
  gzip_vary on;
  #limit_zone  crawler  $binary_remote_addr  10m;
  server
  {
    listen       80;
    server_name  blog.56diy.com;
    index index.html index.htm index.php;
    root  /data/www/blog.56diy.com;
    #limit_conn   crawler  20;    
                             
    location ~ .*\.(php|php5)?$
    {      
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
    
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      30d;
    }
    location ~ .*\.(js|css)?$
    {
      expires      1h;
    }   
    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
              '$status $body_bytes_sent "$http_referer" '
              '"$http_user_agent" $http_x_forwarded_for';
    access_log  /data/logs/blog.56diy.com/access.log  access;
      }
  server
  {
    listen       80;
    server_name  
www.56diy.com ;
    index index.html index.htm index.php;
    root  /data/www/www.56diy.com;
    location ~ .*\.(php|php5)?$
    {      
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
    log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" $http_x_forwarded_for';
    access_log  /data/logs/www.56diy.com/wwwlogs.log  wwwlogs;
  }
  server
  {
    listen  80;
    server_name  status.www.56diy.com;
    location / {
    stub_status on;
    access_log   off;
    }
  }
}
#在/usr/local/nginx/conf/目录中创建fcgi.conf文件
vi /usr/local/nginx/conf/fcgi.conf
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
#启动Nginx
ulimit -SHn 65535
/usr/local/nginx/sbin/nginx
#配置开机自动启动Nginx + PHP
vi /etc/rc.local
ulimit -SHn 65535
/usr/local/php/sbin/php-fpm start
/usr/local/nginx/sbin/nginx

#============================安全优化================================================
#优化Linux内核参数
mv /etc/sysctl.conf /etc/sysctl.conf.bak
vi /etc/sysctl.conf
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog =  32768
net.core.somaxconn = 32768
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_tw_recycle = 1
#net.ipv4.tcp_tw_len = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 120
net.ipv4.ip_local_port_range = 1024  65535
kernel.shmmax = 128000000
#使配置立即生效
/sbin/sysctl -p
#关闭不用服务
vi /etc/service_stop.sh
#!/bin/bash
# This script is used to del some service is not used on the server
# Create by kerryhu
# Date 2010-03-23
# Mail 
king_819@163.com
service  microcode_ctl stop
chkconfig --level 235 microcode_ctl off
service gpm stop
chkconfig --level 235 gpm off
service kudzu stop
chkconfig --level 235 kudzu off
service netfs stop
chkconfig --level 235 netfs off
service rawdevices stop
chkconfig --level 235 rawdevices off
service saslauthd stop
chkconfig --level 235 saslauthd off
service keytable stop
chkconfig --level 235 keytable off
service mdmonitor stop
chkconfig --level 235 mdmonitor off
service atd stop
chkconfig --level 235 atd off
service irda stop
chkconfig --level 235 irda off
service psacct stop
chkconfig --level 235 psacct off
service apmd stop
chkconfig --level 235 apmd off
service isdn stop
chkconfig --level 235 isdn off
service iptables stop
chkconfig --level 235 iptables off
service ip6tables stop
chkconfig --level 235 ip6tables off
service pcmcia stop
chkconfig --level 235 pcmcia off
service sendmail stop
chkconfig --level 235 sendmail off
service smartd stop
chkconfig --level 235 smartd off
service autofs stop
chkconfig --level 235 autofs off
service netdump stop
chkconfig --level 235 netdump off
service portmap stop
chkconfig --level 235 portmap off
service nfs stop
chkconfig --level 235 nfs off
service nfslock stop
chkconfig --level 235 nfslock off
service snmptrapd stop
chkconfig --level 235 snmptrapd off
service rhnsd stop
chkconfig --level 235 rhnsd off
service xinetd stop
chkconfig --level 235 xinetd off
service cups stop
chkconfig --level 235 cups off
service snmpd stop
chkconfig --level 235 snmpd off
service vncserver stop
chkconfig --level 235 vncserver off
service hpoj stop
chkconfig --level 235 hpoj off
service xfs stop
chkconfig --level 235 xfs off
service ntpd stop
chkconfig --level 235 ntpd off
service winbind stop
chkconfig --level 235 winbind off
service smb stop
chkconfig --level 235 smb off
service dc_client stop
chkconfig --level 235 dc_client off
service dc_server stop
chkconfig --level 235 dc_server off
service httpd stop
chkconfig --level 235 httpd off
service aep1000 stop
chkconfig --level 235 aep1000 off
service bcm5820 stop
chkconfig --level 235 bcm5820 off
service squid stop
chkconfig --level 235 squid off
service named stop
chkconfig --level 235 named off
service tux stop
chkconfig --level 235 tux off
service vsftpd stop
chkconfig --level 235 vsftpd off
service avahi-daemon stop
chkconfig --level 235 avahi-daemon  off
service bluetooth stop
chkconfig --level 235 bluetooth off
service firstboot stop
chkconfig --level 235 firstboot off
service lvm2-monitor stop
chkconfig --level 235 lvm2-monitor off
service mcstrans stop
chkconfig --level 235 mcstrans off
service pcscd stop
chkconfig --level 235 pcscd off
service restorecond stop
chkconfig --level 235 restorecond off
service rpcgssd stop
chkconfig --level 235 rpcgssd off
service rpcidmapd stop
chkconfig --level 235 rpcidmapd off
chmod +x /root/service_stop.sh
#执行脚本关闭不需要的服务
/root/service_stop.sh
#iptables设置
vi /root/iptables.sh
#echo "Starting kerryhu-iptables rules..."
#!/bin/bash
#this is a common firewall created by 2010-3-27
 
#define some variable
IPT=/sbin/iptables
CONNECTION_TRACKING="1"
INTERNET="eth0"
CLASS_A="10.0.0.0/8"
CLASS_B="172.16.0.0/12"
CLASS_C="192.168.0.0/16"
CLASS_D_MULTICAST="224.0.0.0/4"
CLASS_E_RESERVED_NET="240.0.0.0/5"
BROADCAST_SRC="0.0.0.0" 
BROADCAST_DEST="255.255.255.255"
LOOPBACK_INTERFACE="lo"
 
#Remove any existing rules
$IPT -F
$IPT -X
 
#setting default firewall policy
$IPT --policy OUTPUT DROP
$IPT --policy FORWARD DROP
$IPT -P INPUT DROP
 
 
#stop firewall
if [ "$1" = "stop" ]
then 
echo "Filewall completely stopped!no firewall running!"
exit 0
fi
 
#setting for loopback interface
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT
 
# Stealth Scans and TCP State Flags
# All of the bits are cleared
$IPT -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
# SYN and FIN are both set
$IPT -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
# SYN and RST are both set
$IPT -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
# FIN and RST are both set
$IPT -A INPUT -p tcp --tcp-flags FIN,RST FIN,RST -j DROP
# FIN is the only bit set, without the expected accompanying ACK
$IPT -A INPUT -p tcp --tcp-flags ACK,FIN FIN -j DROP
# PSH is the only bit set, without the expected accompanying ACK
$IPT -A INPUT -p tcp --tcp-flags ACK,PSH PSH -j DROP
# URG is the only bit set, without the expected accompanying ACK
$IPT -A INPUT -p tcp --tcp-flags ACK,URG URG -j DROP
 
# Using Connection State to By-pass Rule Checking
if [ "$CONNECTION_TRACKING" = "1" ]; then
    $IPT -A INPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPT -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPT -A INPUT -m state --state INVALID -j DROP
    $IPT -A OUTPUT -m state --state INVALID -j DROP
fi
 
##################################################################
# Source Address Spoofing and Other Bad Addresses
 
# Refuse spoofed packets pretending to be from 
# the external interface.s IP address
 
# Refuse packets claiming to be from a Class A private network
$IPT -A INPUT  -i $INTERNET -s $CLASS_A -j DROP
 
# Refuse packets claiming to be from a Class B private network
$IPT -A INPUT  -i $INTERNET -s $CLASS_B -j DROP
 
# Refuse packets claiming to be from a Class C private network
$IPT -A INPUT  -i $INTERNET -s $CLASS_C -j DROP
 
$IPT -A INPUT -i $INTERNET -s 0.0.0.0/8 -j DROP
$IPT -A INPUT -i $INTERNET -s 169.254.0.0/16 -j DROP
$IPT -A INPUT -i $INTERNET -s 192.0.2.0/24 -j DROP
###################################################################
#setting access rules
 
#enable ssh connect
#$IPT -A OUTPUT  -o $INTERNET -p tcp  -d 61.177.7.1 -j ACCEPT
#时钟同步
$IPT -A OUTPUT -d 192.43.244.18 -j ACCEPT
#允许ping出
$IPT -A OUTPUT -p icmp -j ACCEPT
$IPT -A OUTPUT -o $INTERNET -p udp  --dport 53 -j ACCEPT
$IPT -A OUTPUT -o $INTERNET -p tcp  --dport 80 -j ACCEPT
$IPT -A INPUT -i $INTERNET -p tcp -m mac --mac-source 00:02:3F:EB:E2:01  --dport 22 -j ACCEPT
$IPT -A INPUT -i $INTERNET -p tcp  --dport 443 -j ACCEPT
$IPT -A INPUT -i $INTERNET -p tcp  --dport 80 -j ACCEPT
$IPT -A INPUT -i $INTERNET -p tcp -s 127.0.0.1 --dport 3306 -j ACCEPT
$IPT -A INPUT -i $INTERNET -p udp  --dport 123 -j ACCEPT
chmod +x /root/iptables.sh
echo "/root/iptables.sh" >> /etc/rc.local
#=======================在不停止Nginx服务的情况下平滑变更Nginx配置======================================
1、修改/usr/local/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
/usr/local/nginx/sbin/nginx -t
/*
如果屏幕显示以下两行信息,说明配置文件正确:
the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully
*/
2、平滑重启:
①、对于Nginx 0.8.x版本,现在平滑重启Nginx配置非常简单,执行以下命令即可:
/usr/local/nginx/sbin/nginx -s reload

②、对于Nginx 0.8.x之前的版本,平滑重启稍微麻烦一些,按照以下步骤进行即可。输入以下命令查看Nginx主进程号:
ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'
屏幕显示的即为Nginx主进程号,例如:
6302
这时,执行以下命令即可使修改过的Nginx配置文件生效:
kill -HUP 6302
#或者无需这么麻烦,找到Nginx的Pid文件:
kill -HUP `cat /usr/local/nginx/nginx.pid`

#===========================编写每天定时切割Nginx日志的脚本==============================================
vi /usr/local/nginx/sbin/cut_nginx_log.sh
#!/bin/bash
# This script run at 00:00
# The Nginx logs path
logs_path_blog="/data/logs/blog.56diy.com/"
logs_path_www="/data/logs/www.56diy.com/"
mkdir -p ${logs_path_blog}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path_blog}access.log ${logs_path_blog}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log
mkdir -p ${logs_path_www}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/
mv ${logs_path_www}wwwlogs.log ${logs_path_www}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/wwwlogs_$(date -d "yesterday" +"%Y%m%d").log
kill -USR1 `cat /usr/local/nginx/nginx.pid`
chmod +x /usr/local/nginx/sbin/cut_nginx_log.sh
#添加计划任务,每天凌晨00:00切割nginx访问日志
crontab -e
00 00 * * * /bin/bash  /usr/local/nginx/sbin/cut_nginx_log.sh
#====================================故障排查===========================================
#故障1
/usr/local/php/sbin/php-fpm start
Starting php_fpm eAccelerator: Could not allocate 67108864 bytes, the maximum size the kernel allows is 33554432 bytes. Lower the amount of memory request or increase the limit in /proc/sys/kernel/shmmax.
PHP Warning:  [eAccelerator] Can not create shared memory area in Unknown on line 0
PHP Fatal error:  Unable to start eAccelerator module in Unknown on line 0
 failed
 
#说明
php.ini中设置的eAccelerator,eaccelerator.shm_size="64",解释:eaccelerator可使用的共享内存大小(单位为MB),即64M
在Linux下,单个进程的最大内存使用量受/proc/sys/kernel/shmmax中设置的数字限制(单位为字节)  /proc/sys/kernel/shmmax = 33554432 (32M)
临时更改该值:
echo 128000000 > /proc/sys/kernel/shmmax
或者
vi /etc/sysctl.conf
kernel.shmmax = 128000000
syscatl -p


本文转自king_819 51CTO博客,原文链接:http://blog.51cto.com/kerry/289485,如需转载请自行联系原作者
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
15天前
|
安全 开发工具 Swift
Swift 是苹果公司开发的现代编程语言,具备高效、安全、简洁的特点,支持类型推断、闭包、泛型等特性,广泛应用于苹果各平台及服务器端开发
Swift 是苹果公司开发的现代编程语言,具备高效、安全、简洁的特点,支持类型推断、闭包、泛型等特性,广泛应用于苹果各平台及服务器端开发。基础语法涵盖变量、常量、数据类型、运算符、控制流等,高级特性包括函数、闭包、类、结构体、协议和泛型。
25 2
|
2月前
|
NoSQL Linux Redis
在 centos7 下重启/开启 redis 服务器
本文提供了一种在Centos 7操作系统下如何重启Redis服务器的步骤,包括停止Redis服务、确认停止成功以及重新启动Redis服务。
151 2
在 centos7 下重启/开启 redis 服务器
|
2月前
|
SQL 安全 网络安全
守护数字资产:服务器迁移期间的安全挑战与对策
【10月更文挑战第4天】在数字化转型的浪潮中,服务器迁移成为企业不可避免的任务。然而,迁移过程中的安全挑战不容忽视。本文从安全考量的角度,探讨了服务器迁移期间可能遇到的安全问题,并提供了相应的对策和代码示例。
75 3
|
2月前
|
存储 网络协议 Linux
AWS实操-EC2-创建购买linux(centos)EC2服务器
AWS实操-EC2-创建购买linux(centos)EC2服务器
|
2月前
|
弹性计算 关系型数据库 MySQL
CentOS 7.x操作系统的ECS云服务器上搭建WordPress网站
CentOS 7.x操作系统的ECS云服务器上搭建WordPress网站
|
2月前
|
Linux 数据安全/隐私保护 Windows
centos 7.2 搭建svn服务器
centos 7.2 搭建svn服务器
53 0
|
16天前
|
人工智能 弹性计算 编解码
阿里云GPU云服务器性能、应用场景及收费标准和活动价格参考
GPU云服务器作为阿里云提供的一种高性能计算服务,通过结合GPU与CPU的计算能力,为用户在人工智能、高性能计算等领域提供了强大的支持。其具备覆盖范围广、超强计算能力、网络性能出色等优势,且计费方式灵活多样,能够满足不同用户的需求。目前用户购买阿里云gpu云服务器gn5 规格族(P100-16G)、gn6i 规格族(T4-16G)、gn6v 规格族(V100-16G)有优惠,本文为大家详细介绍阿里云gpu云服务器的相关性能及收费标准与最新活动价格情况,以供参考和选择。
|
21天前
|
机器学习/深度学习 人工智能 弹性计算
什么是阿里云GPU云服务器?GPU服务器优势、使用和租赁费用整理
阿里云GPU云服务器提供强大的GPU算力,适用于深度学习、科学计算、图形可视化和视频处理等多种场景。作为亚太领先的云服务提供商,阿里云的GPU云服务器具备灵活的资源配置、高安全性和易用性,支持多种计费模式,帮助企业高效应对计算密集型任务。
|
23天前
|
存储 分布式计算 固态存储
阿里云2核16G、4核32G、8核64G配置云服务器租用收费标准与活动价格参考
2核16G、8核64G、4核32G配置的云服务器处理器与内存比为1:8,这种配比的云服务器一般适用于数据分析与挖掘,Hadoop、Spark集群和数据库,缓存等内存密集型场景,因此,多为企业级用户选择。目前2核16G配置按量收费最低收费标准为0.54元/小时,按月租用标准收费标准为260.44元/1个月。4核32G配置的阿里云服务器按量收费标准最低为1.08元/小时,按月租用标准收费标准为520.88元/1个月。8核64G配置的阿里云服务器按量收费标准最低为2.17元/小时,按月租用标准收费标准为1041.77元/1个月。本文介绍这些配置的最新租用收费标准与活动价格情况,以供参考。
|
21天前
|
机器学习/深度学习 人工智能 弹性计算
阿里云GPU服务器全解析_GPU价格收费标准_GPU优势和使用说明
阿里云GPU云服务器提供强大的GPU算力,适用于深度学习、科学计算、图形可视化和视频处理等场景。作为亚太领先的云服务商,阿里云GPU云服务器具备高灵活性、易用性、容灾备份、安全性和成本效益,支持多种实例规格,满足不同业务需求。
114 2