CentOS7安裝PHP開發環境1-源碼安裝Nginx

OS:CentOS 7
Nginx:1.16.0

安裝後的腳本

重啓nginx、PHP腳本

cat /auto.sh

# /bin/bash
#Nginx
NGINXPID_PATH='/application/nginx/logs/nginx.pid'
if [ -e ${NGINXPID_PATH} ];then
        /application/nginx/sbin/nginx -s reload
else
        /application/nginx/sbin/nginx
fi

#php-fpm
PHPPID_PATH="/application/php/var/run/php-fpm.pid"
if [ -e ${PHPPID_PATH} ];then
        kill -USR2 `cat ${PHPPID_PATH}`
else
        /application/php/sbin/php-fpm
fi

#/application/nginx/sbin/nginx -s reload
#kill -USR2 `cat /application/php5.6.32/var/run/php-fpm.pid`
#kill -USR2 `cat /application/php7.2.1/var/run/php-fpm.pid` 
#/application/nginx/sbin/nginx -s stop
#killall php-fpm
#sleep 0.5
#umount -f /wwwroot
#mount -t vboxsf wwwroot /wwwroot
#sleep 0.1
#/application/php5.6.32/sbin/php-fpm
#/application/php7.2.1/sbin/nginx
#/application/nginx/sbin/nginx
#echo 'OK'

開機啓動腳本

cat /etc/rc.local

#!/bin/bash
touch /var/lock/subsys/local

mount -t vboxsf wwwroot /wwwroot
#開機啓動redis服務 3.2.9
#/application/redis/src/redis-server &
/application/redis/src/redis-server  /application/redis/redis.conf
#開機啓動memcached服務
/usr/bin/memcached -d -l 127.0.0.1 -p 11211 -m 256 -u root
#開機啓動php-fpm 7.1.6
###/application/php/bin/php-cgi -b 127.0.0.1:9000 -c /application/php/etc/php.ini
/application/php/sbin/php-fpm
#開機啓動Nginx服務器 1.16.0
###/application/nginx/sbin/nginx -c /application/nginx/conf/nginx.conf
/application/nginx/sbin/nginx

安裝前的準備

yum卸載
# yum remove 包名
yum -y update
yum install -y g++ gcc gcc-c++ vim wget psmisc net-tools zip unzip m4 autoconf automake libzip*
yum install -y bzip2* curl curl-devel libicu-devel make
yum install -y bison-devel ncurses-devel libaio libaio-devel perl-Data-Dumper
說明

#psmisc                                            # killall
#net-tools                                         # ifconfig
#m4 autoconf                                   # php/bin/phpize 安裝擴展
#zip  unzip                                        #
#bzip2*                                             #  增強工具用的是bzip2壓縮

yum -y install make kernel-* # 主要是在安裝增強工具提示沒有安裝這些軟件
yum -y install libevent # 爲了安裝memcached
yum install -y libxml2*
yum install -y openssl openssl-devel
yum install -y re2c freetype* libwebp* libjpeg* libpng* libXpm* libacl* icu cmake bison zlib* pcre* systemtap-sdt*

1.安裝Nginx所需的pcre庫

pcre的全稱爲perl compatible regular expressions,中文譯爲“perl兼容正則表達式”,官方站點爲 http://www.pcre.org/ ,安裝pcre庫是爲了使Nginx支持具備URI重寫功能的rewrite模塊,如果不安裝pcre庫,則Nginx無法使用rewrite模塊功能,Nginx的rewrite模塊功能幾乎是企業應用必須的。安裝pcre庫的過程如下。

[root@sy-pc ~]# yum install pcre pcre-devel -y
[root@sy-pc ~]# rpm -qa pcre pcre-devel
pcre-devel-8.32-17.el7.x86_64
pcre-8.32-17.el7.x86_64

2.安裝Nginx所需的openssl庫

[root@sy-pc ~]# yum install openssl openssl-devel -y
[root@sy-pc ~]# rpm -qa openssl openssl-devel
openssl-devel-1.0.2k-16.el7_6.1.x86_64
openssl-1.0.2k-16.el7_6.1.x86_64

3.安裝zlib

[root@sy-pc ~]# yum install zlib zlib-devel -y
[root@sy-pc ~]# rpm -qa zlib zlib-devel
zlib-1.2.7-18.el7.x86_64
zlib-devel-1.2.7-18.el7.x86_64

安裝Nginx

創建nginx用戶

# useradd nginx -s /sbin/nologin -M

下載:http://nginx.org/download/nginx-1.16.0.tar.gz

[root@sy-pc ~]# mkdir /tools
[root@sy-pc ~]# cd /tools
[root@sy-pc tools]# wget http://nginx.org/download/nginx-1.16.0.tar.gz
[root@sy-pc tools]# ll
total 1012
-rw-r--r--. 1 root root 1032345 Apr 23 21:58 nginx-1.16.0.tar.gz

解壓

[root@sy-pc tools]# tar -zxvf nginx-1.16.0.tar.gz
[root@sy-pc tools]# cd nginx-1.16.0

tar xf nginx-1.16.0.tar.gz ,則不顯示解壓過程。

使用./configure --help查看相關參數。

# ./configure --help

  --help                             print this message

  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --modules-path=PATH                set modules path
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set nginx.pid pathname
  --lock-path=PATH                   set nginx.lock pathname

  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes

  --build=NAME                       set build name
  --builddir=DIR                     set build directory

  --with-select_module               enable select module
  --without-select_module            disable select module
  --with-poll_module                 enable poll module
  --without-poll_module              disable poll module

  --with-threads                     enable thread pool support

  --with-file-aio                    enable file AIO support

  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
  --with-http_image_filter_module=dynamic
                                     enable dynamic ngx_http_image_filter_module
  --with-http_geoip_module           enable ngx_http_geoip_module
  --with-http_geoip_module=dynamic   enable dynamic ngx_http_geoip_module
  --with-http_sub_module             enable ngx_http_sub_module
  --with-http_dav_module             enable ngx_http_dav_module
  --with-http_flv_module             enable ngx_http_flv_module
  --with-http_mp4_module             enable ngx_http_mp4_module
  --with-http_gunzip_module          enable ngx_http_gunzip_module
  --with-http_gzip_static_module     enable ngx_http_gzip_static_module
  --with-http_auth_request_module    enable ngx_http_auth_request_module
  --with-http_random_index_module    enable ngx_http_random_index_module
  --with-http_secure_link_module     enable ngx_http_secure_link_module
  --with-http_degradation_module     enable ngx_http_degradation_module
  --with-http_slice_module           enable ngx_http_slice_module
  --with-http_stub_status_module     enable ngx_http_stub_status_module

  --without-http_charset_module      disable ngx_http_charset_module
  --without-http_gzip_module         disable ngx_http_gzip_module
  --without-http_ssi_module          disable ngx_http_ssi_module
  --without-http_userid_module       disable ngx_http_userid_module
  --without-http_access_module       disable ngx_http_access_module
  --without-http_auth_basic_module   disable ngx_http_auth_basic_module
  --without-http_mirror_module       disable ngx_http_mirror_module
  --without-http_autoindex_module    disable ngx_http_autoindex_module
  --without-http_geo_module          disable ngx_http_geo_module
  --without-http_map_module          disable ngx_http_map_module
  --without-http_split_clients_module disable ngx_http_split_clients_module
  --without-http_referer_module      disable ngx_http_referer_module
  --without-http_rewrite_module      disable ngx_http_rewrite_module
  --without-http_proxy_module        disable ngx_http_proxy_module
  --without-http_fastcgi_module      disable ngx_http_fastcgi_module
  --without-http_uwsgi_module        disable ngx_http_uwsgi_module
  --without-http_scgi_module         disable ngx_http_scgi_module
  --without-http_grpc_module         disable ngx_http_grpc_module
  --without-http_memcached_module    disable ngx_http_memcached_module
  --without-http_limit_conn_module   disable ngx_http_limit_conn_module
  --without-http_limit_req_module    disable ngx_http_limit_req_module
  --without-http_empty_gif_module    disable ngx_http_empty_gif_module
  --without-http_browser_module      disable ngx_http_browser_module
  --without-http_upstream_hash_module
                                     disable ngx_http_upstream_hash_module
  --without-http_upstream_ip_hash_module
                                     disable ngx_http_upstream_ip_hash_module
  --without-http_upstream_least_conn_module
                                     disable ngx_http_upstream_least_conn_module
  --without-http_upstream_random_module
                                     disable ngx_http_upstream_random_module
  --without-http_upstream_keepalive_module
                                     disable ngx_http_upstream_keepalive_module
  --without-http_upstream_zone_module
                                     disable ngx_http_upstream_zone_module

  --with-http_perl_module            enable ngx_http_perl_module
  --with-http_perl_module=dynamic    enable dynamic ngx_http_perl_module
  --with-perl_modules_path=PATH      set Perl modules path
  --with-perl=PATH                   set perl binary pathname

  --http-log-path=PATH               set http access log pathname
  --http-client-body-temp-path=PATH  set path to store
                                     http client request body temporary files
  --http-proxy-temp-path=PATH        set path to store
                                     http proxy temporary files
  --http-fastcgi-temp-path=PATH      set path to store
                                     http fastcgi temporary files
  --http-uwsgi-temp-path=PATH        set path to store
                                     http uwsgi temporary files
  --http-scgi-temp-path=PATH         set path to store
                                     http scgi temporary files

  --without-http                     disable HTTP server
  --without-http-cache               disable HTTP cache

  --with-mail                        enable POP3/IMAP4/SMTP proxy module
  --with-mail=dynamic                enable dynamic POP3/IMAP4/SMTP proxy module
  --with-mail_ssl_module             enable ngx_mail_ssl_module
  --without-mail_pop3_module         disable ngx_mail_pop3_module
  --without-mail_imap_module         disable ngx_mail_imap_module
  --without-mail_smtp_module         disable ngx_mail_smtp_module

  --with-stream                      enable TCP/UDP proxy module
  --with-stream=dynamic              enable dynamic TCP/UDP proxy module
  --with-stream_ssl_module           enable ngx_stream_ssl_module
  --with-stream_realip_module        enable ngx_stream_realip_module
  --with-stream_geoip_module         enable ngx_stream_geoip_module
  --with-stream_geoip_module=dynamic enable dynamic ngx_stream_geoip_module
  --with-stream_ssl_preread_module   enable ngx_stream_ssl_preread_module
  --without-stream_limit_conn_module disable ngx_stream_limit_conn_module
  --without-stream_access_module     disable ngx_stream_access_module
  --without-stream_geo_module        disable ngx_stream_geo_module
  --without-stream_map_module        disable ngx_stream_map_module
  --without-stream_split_clients_module
                                     disable ngx_stream_split_clients_module
  --without-stream_return_module     disable ngx_stream_return_module
  --without-stream_upstream_hash_module
                                     disable ngx_stream_upstream_hash_module
  --without-stream_upstream_least_conn_module
                                     disable ngx_stream_upstream_least_conn_module
  --without-stream_upstream_random_module
                                     disable ngx_stream_upstream_random_module
  --without-stream_upstream_zone_module
                                     disable ngx_stream_upstream_zone_module

  --with-google_perftools_module     enable ngx_google_perftools_module
  --with-cpp_test_module             enable ngx_cpp_test_module

  --add-module=PATH                  enable external module
  --add-dynamic-module=PATH          enable dynamic external module

  --with-compat                      dynamic modules compatibility

  --with-cc=PATH                     set C compiler pathname
  --with-cpp=PATH                    set C preprocessor pathname
  --with-cc-opt=OPTIONS              set additional C compiler options
  --with-ld-opt=OPTIONS              set additional linker options
  --with-cpu-opt=CPU                 build for the specified CPU, valid values:
                                     pentium, pentiumpro, pentium3, pentium4,
                                     athlon, opteron, sparc32, sparc64, ppc64

  --without-pcre                     disable PCRE library usage
  --with-pcre                        force PCRE library usage
  --with-pcre=DIR                    set path to PCRE library sources
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-pcre-jit                    build PCRE with JIT compilation support

  --with-zlib=DIR                    set path to zlib library sources
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-zlib-asm=CPU                use zlib assembler sources optimized
                                     for the specified CPU, valid values:
                                     pentium, pentiumpro

  --with-libatomic                   force libatomic_ops library usage
  --with-libatomic=DIR               set path to libatomic_ops library sources

  --with-openssl=DIR                 set path to OpenSSL library sources
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL

  --with-debug                       enable debug logging

部分參數說明:
--prefix=PATH set installation prefix#設置安裝路徑
--user=USER set non-privileged user for worker processes#進程用戶權限
--group=GROUP set non-privileged group for worker processes#進程用戶組權限
--with-http_stub_status_module enable ngx_http_stub_status_module#激活狀態信息
--with-http_ssl_module enable ngx_http_ssl_module#激活SSL功能

配置命令:./configure --user=nginx --group=nginx --prefix=/application/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module

[root@sy-pc nginx-1.16.0]# ./configure --user=nginx --group=nginx --prefix=/application/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module

屏幕將輸出以下內容:

checking for OS
 + Linux 3.10.0-514.el7.x86_64 x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC) 
checking for gcc -pipe switch ... found
checking for -Wl,-E switch ... found
checking for gcc builtin atomic operations ... found
checking for C99 variadic macros ... found
checking for gcc variadic macros ... found
checking for gcc builtin 64 bit byteswap ... found
checking for unistd.h ... found
checking for inttypes.h ... found
checking for limits.h ... found
checking for sys/filio.h ... not found
checking for sys/param.h ... found
checking for sys/mount.h ... found
checking for sys/statvfs.h ... found
checking for crypt.h ... found
checking for Linux specific features
checking for epoll ... found
checking for EPOLLRDHUP ... found
checking for EPOLLEXCLUSIVE ... not found
checking for O_PATH ... found
checking for sendfile() ... found
checking for sendfile64() ... found
checking for sys/prctl.h ... found
checking for prctl(PR_SET_DUMPABLE) ... found
checking for prctl(PR_SET_KEEPCAPS) ... found
checking for capabilities ... found
checking for crypt_r() ... found
checking for sys/vfs.h ... found
checking for poll() ... found
checking for /dev/poll ... not found
checking for kqueue ... not found
checking for crypt() ... not found
checking for crypt() in libcrypt ... found
checking for F_READAHEAD ... not found
checking for posix_fadvise() ... found
checking for O_DIRECT ... found
checking for F_NOCACHE ... not found
checking for directio() ... not found
checking for statfs() ... found
checking for statvfs() ... found
checking for dlopen() ... not found
checking for dlopen() in libdl ... found
checking for sched_yield() ... found
checking for sched_setaffinity() ... found
checking for SO_SETFIB ... not found
checking for SO_REUSEPORT ... found
checking for SO_ACCEPTFILTER ... not found
checking for SO_BINDANY ... not found
checking for IP_TRANSPARENT ... found
checking for IP_BINDANY ... not found
checking for IP_BIND_ADDRESS_NO_PORT ... not found
checking for IP_RECVDSTADDR ... not found
checking for IP_SENDSRCADDR ... not found
checking for IP_PKTINFO ... found
checking for IPV6_RECVPKTINFO ... found
checking for TCP_DEFER_ACCEPT ... found
checking for TCP_KEEPIDLE ... found
checking for TCP_FASTOPEN ... found
checking for TCP_INFO ... found
checking for accept4() ... found
checking for eventfd() ... found
checking for int size ... 4 bytes
checking for long size ... 8 bytes
checking for long long size ... 8 bytes
checking for void * size ... 8 bytes
checking for uint32_t ... found
checking for uint64_t ... found
checking for sig_atomic_t ... found
checking for sig_atomic_t size ... 4 bytes
checking for socklen_t ... found
checking for in_addr_t ... found
checking for in_port_t ... found
checking for rlim_t ... found
checking for uintptr_t ... uintptr_t found
checking for system byte ordering ... little endian
checking for size_t size ... 8 bytes
checking for off_t size ... 8 bytes
checking for time_t size ... 8 bytes
checking for AF_INET6 ... found
checking for setproctitle() ... not found
checking for pread() ... found
checking for pwrite() ... found
checking for pwritev() ... found
checking for sys_nerr ... found
checking for localtime_r() ... found
checking for clock_gettime(CLOCK_MONOTONIC) ... found
checking for posix_memalign() ... found
checking for memalign() ... found
checking for mmap(MAP_ANON|MAP_SHARED) ... found
checking for mmap("/dev/zero", MAP_SHARED) ... found
checking for System V shared memory ... found
checking for POSIX semaphores ... not found
checking for POSIX semaphores in libpthread ... found
checking for struct msghdr.msg_control ... found
checking for ioctl(FIONBIO) ... found
checking for struct tm.tm_gmtoff ... found
checking for struct dirent.d_namlen ... not found
checking for struct dirent.d_type ... found
checking for sysconf(_SC_NPROCESSORS_ONLN) ... found
checking for sysconf(_SC_LEVEL1_DCACHE_LINESIZE) ... found
checking for openat(), fstatat() ... found
checking for getaddrinfo() ... found
checking for PCRE library ... found
checking for PCRE JIT support ... found
checking for OpenSSL library ... found
checking for zlib library ... found
creating objs/Makefile

Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library

  nginx path prefix: "/application/nginx-1.16.0"
  nginx binary file: "/application/nginx-1.16.0/sbin/nginx"
  nginx modules path: "/application/nginx-1.16.0/modules"
  nginx configuration prefix: "/application/nginx-1.16.0/conf"
  nginx configuration file: "/application/nginx-1.16.0/conf/nginx.conf"
  nginx pid file: "/application/nginx-1.16.0/logs/nginx.pid"
  nginx error log file: "/application/nginx-1.16.0/logs/error.log"
  nginx http access log file: "/application/nginx-1.16.0/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"
[root@sy-pc nginx-1.16.0]# make && make install
# ln -s /application/nginx-1.16.0 /application/nginx

查看軟連接

# ll /application | grep nginx
lrwxrwxrwx. 1 root root 26 Aug  5 17:57 nginx -> /application/nginx-1.16.0/
drwxr-xr-x. 6 root root 54 Aug  5 17:57 nginx-1.16.0

檢查安裝結果並啓動

(1)啓動前檢查配置文件語法

[root@sy-pc ~]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.16.0/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.16.0/conf/nginx.conf test is successful

(2)啓動Nginx服務

/application/nginx/sbin/nginx

(3)查看Nginx服務對應的端口是否成功啓動

三個命令任意使用一個。

# netstat -lntup|grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      13924/nginx: master 
# lsof -i:80
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   13924  root    6u  IPv4  29420      0t0  TCP *:http (LISTEN)
nginx   13925 nginx    6u  IPv4  29420      0t0  TCP *:http (LISTEN)
# ps -ef|grep nginx|grep -v grep
root     13924     1  0 18:13 ?        00:00:00 nginx: master process /application/nginx/sbin/nginx
nginx    13925 13924  0 18:13 ?        00:00:00 nginx: worker process

Nginx相關命令

/application/nginx/sbin/nginx -t檢查配置文件語法
/application/nginx/sbin/nginx -s stop|quit|reopen|reload
/application/nginx/sbin/nginx啓動
/application/nginx/sbin/nginx -s stop停止
/application/nginx/sbin/nginx -s reload平滑重啓

查看編譯時的參數配置

# /application/nginx/sbin/nginx -V
nginx version: nginx/1.16.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --user=nginx --group=nginx --prefix=/application/nginx-1.16.0 --with-http_stub_status_module --with-http_ssl_module

其他命令

[root@sy-pc ~]# /application/nginx/sbin/nginx -h
nginx version: nginx/1.16.0
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /application/nginx-1.16.0/)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file

開機啓動

爲 開機啓動腳本 添加可執行權限。

[root@sy-pc ~]# ll /etc/rc.local 
lrwxrwxrwx. 1 root root 13 Aug  5 16:55 /etc/rc.local -> rc.d/rc.local
[root@sy-pc ~]# ll /etc/rc.d/rc.local 
-rw-r--r--. 1 root root 473 Nov  7  2016 /etc/rc.d/rc.local
[root@sy-pc ~]# chmod +x /etc/rc.d/rc.local 
[root@sy-pc ~]# ll /etc/rc.d/rc.local 
-rwxr-xr-x. 1 root root 473 Nov  7  2016 /etc/rc.d/rc.local

添加Nginx啓動命令

[root@sy-pc ~]# cat >> /etc/rc.local << EOF
> #開機啓動Nginx服務器 1.16.0
> #/application/nginx/sbin/nginx -c /application/nginx/conf/nginx.conf
> /application/nginx/sbin/nginx
> EOF

非root用戶啓動(本節作廢)

修改nginx的二進制啓動文件

# chown root:sy /application/nginx/sbin/nginx
# chmod +s /application/nginx/sbin/nginx

$ ll /application/nginx/sbin/nginx 
-rwsr-xr-x. 1 root sy 5586599 Jun 28  2017 /application/nginx/sbin/nginx

則nginx二進制文件的原屬主sy、原屬組sy,被改成屬主root、屬組sy。
則開機腳本/etc/rc.local可以寫爲:

#/application/nginx/sbin/nginx -c /application/nginx/conf/nginx.conf
su - sy << EOF
/application/nginx/sbin/nginx
EOF

查看進程,發現主進程是root,子進程是sy

# ps -ef|grep nginx|grep -v grep
root      3630     1  0 Aug03 ?        00:00:00 nginx: master process /application/nginx/sbin/nginx
sy        3631  3630  0 Aug03 ?        00:00:00 nginx: worker process

添加虛擬主機

可以修改vim /application/nginx/conf/nginx.conf,在http{}代碼塊中添加一句
include /wwwroot/nginx_vhost/*.conf;
然後在對應的/wwwroot/nginx_vhost/目錄下新建一個文件 p7height.net.conf;內容如下:

server {
    listen       80;
    server_name  p7height.net   www.p7height.net;
    root   /wwwroot/p7height.net;
    location / {
        index  index.html index.htm default.html default.htm index.php default.php app.php u.php;
        include        /wwwroot/p7height.net/up-*.conf;
    }
    autoindex off;
    #include advanced_settings.conf;
    #include expires.conf;
    location ~* .*\/(attachment|attachments|uploadfiles|avatar)\/.*\.(php|php5|phps|asp|aspx|jsp)$ {
        deny all;
    }
    location ~ ^.+\.php {
        fastcgi_pass   127.0.0.1:9000;       
    #    fastcgi_pass   bakend;
        fastcgi_index  index.php;
        fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
        #fastcgi_param  PATH_INFO $fastcgi_path_info;
        fastcgi_param  PATH_TRANSLATED $document_root$fastcgi_path_info;
        include        fastcgi.conf;
    }
}

fastcgi_param PATH_INFO $fastcgi_path_info;fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;,任選其一。

關閉sendfile ,Linux中的“零拷貝”

如果開發環境使用了mount掛載目錄,那麼在修改了靜態文件後,避免網頁讀取靜態文件不完整(在瀏覽器中查看網頁源代碼,發現未加載編輯後的代碼,且文件末尾有很多菱形字符),就需要關閉sendfile;
修改:vim /application/nginx/conf/nginx.conf
sendfile on;
改爲 sendfile off;

關閉防火牆:

systemctl stop firewalld.service #停止firewall
systemctl disable firewalld.service #禁止firewall開機啓動
firewall-cmd --state #查看默認防火牆狀態(關閉後顯示not running,開啓後顯示running)

Nginx支持HTTPS

http強制跳轉到HTTPS
參考:http://blog.csdn.net/u013216667/article/details/53467319
參考:http://www.cnblogs.com/Tiago/p/6236595.html

生成證書
在服務器的命令行下進行如下操作
創建目錄、並進入該目錄
/application/nginx/ck/
①生成服務端的私鑰,需要輸入一個4~8191位的密碼
openssl genrsa -des3 -out server.key 1024

[root@sy-pc ck]# openssl genrsa -des3 -out server.key 1024
Generating RSA private key, 1024 bit long modulus
................++++++
......................................................................................++++++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

②生成csr文件,這一步需要輸入多種信息,可以全部按回車跳過
openssl req -new -key server.key -out server.csr

[root@sy-pc ck]# openssl req -new -key server.key -out server.csr
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

③生成crt文件,這一步中的-days後爲有效期,可以寫長一點
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

[root@sy-pc ck]# openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
Signature ok
subject=/C=CN/ST=Shanghai/L=Shanghai/O=Shanghai Information/OU=Shanghai Unit Information/CN=*.zhousuyang.com/[email protected]
Getting Private key
Enter pass phrase for server.key:

④Nginx配置SSL安全證書避免啓動輸入Enter PEM pass phrase 參考:http://wangye.org/blog/archives/243/
[root@sy-pc ck]# openssl rsa -in server.key -out server.key.unsecure
Enter pass phrase for server.key:
writing RSA key

不要理下面這句:
這句是幹嘛用的?爲什麼要合併?
[root@sy-pc ck]# cat server.crt server.key > server.pem

http強制跳轉到HTTPS

Nginx的虛擬機配置。
注意fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

server{
    listen 80; 
    server_name     p7height.net;
    return  301     https://p7height.net$request_uri;
}
server {
    listen  443     default_server ssl ;   #default_server ssl 不需要
    server_name  p7height.net;
    ssl     on;               #nginx-1.16版,則不需要這句。
    ssl_certificate         /application/nginx/ck/server.crt;
    #ssl_certificate_key     /application/nginx/ck/server.key;     #但是每次重啓nginx時都要輸入密碼 Enter PEM pass phrase:
    ssl_certificate_key     /application/nginx/ck/server.key.unsecure;     #重啓nginx時不需要輸入密碼
    root                    /wwwroot/p7height.net;
    location / { 
        index  index.html index.htm index.php;
    }   
    #error_page   500 502 503 504  /50x.html;
    #location = /50x.html {
    #}  
    location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }   
    location ~ /\.ht {
        deny  all;
    }   
} 

1.13.1版本

server{
	******
	listen  443;
	ssl     on;
	******
}

1.16.0版本

server{
	******
	listen  443  ssl; #或者省略 ssl
	******
}

隱藏響應頭部的X-Powered-By

Response Headers  
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Wed, 12 Jul 2017 12:48:17 GMT
Server:nginx/1.13.1
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:PHP/7.2.1

在這裏插入圖片描述

一、如果是Nginx服務器,則可以在http、server、location區段中添加如下。在server中添加即可。
proxy_hide_header X-Powered-By; #在proxy模式下起作用
fastcgi_hide_header X-Powered-By; #在fastcgi模式下起作用
二、修改php.ini文件,如下。
expose_php=Off

隱藏/修改 響應頭部的Server

一、Nginx配置文件的http段、或server段添加
server_tokens off; #off隱藏server版本號 on顯示server版本號
二、源文件修改後重新編譯安裝
修改Nginx源文件/src/http/ngx_http_header_filter_module.c

static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
static u_char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
static u_char ngx_http_server_build_string[] = "Server: " NGINX_VER_BUILD CRLF;

改爲:

static u_char ngx_http_server_string[] = "Server: gws" CRLF;
static u_char ngx_http_server_full_string[] = "Server: gws" CRLF;
static u_char ngx_http_server_build_string[] = "Server: gws" CRLF;

錯誤日誌error_log配置

error_log,可以放在Main區塊中全局配置,也可以放置不同的虛擬主機中單獨記錄。

[root@sy-pc ~]# head -8 /application/nginx/conf/nginx.conf 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

error_log的語法格式及參數語法說明如下:

error_log 日誌文件 級別

其中,關鍵字error_log不能改變,日誌文件可以指定任意存放日誌的目錄,錯誤日誌級別常見的有[debug|info|notice|warn|error|crit|alert|emerg],級別越高,記錄的信息越少,生產場景一般是warn|error|crit這三個級別之一,注意不要配置info等較低級別,會帶來巨大磁盤I/O消耗。

可以放置的標籤段爲:
#context: main, http, mail, stream, server, location

Syntax:		error_log file [level];
Default:	error_log logs/error.log error;
Context:	main, http, mail, stream, server, location

參考資料:http://nginx.org/en/docs/ngx_core_module.html#error_log 。

訪問日誌access_log配置

不記錄不需要的訪問日誌

在實際工作中,對於負載均衡器健康節點檢查或某些特定文件(比如圖片、JS、CSS)的日誌,一般不需要記錄下來,因爲在統計PV時是按照頁面計算的,而且日誌寫入太頻繁會消耗大量磁盤I/O,降低服務的性能。

具體配置方法如下:

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
	access_log off;
}

這裏用location標籤匹配不記錄日誌的元素擴展名,然後關掉日誌。

訪問日誌的權限設置

假如日誌目錄爲/app/logs,則授權方法如下:

chown -R root.root /app/logs
chmod -R 700 /app/logs

不需要在日誌目錄上給Nginx用戶讀或寫許可,但很多網友都沒注意這個問題,他們把該權限直接給了Nginx或Apache用戶,這就成爲安全隱患。

Nginx訪問控制

根據擴展名限制程序和文件訪問

Web 2.0時代,絕大多數網站都是以用戶爲中心的,例如:bbs、blog、sns產品,這幾個產品都有一個共同特點,就是不但允許用戶發佈內容到服務器,還允許用戶發圖片甚至上傳附件到服務器上,由於爲用戶開了上傳的功能,因此給服務器帶來了很大的安全風險。雖然很多程序在上傳前會做一定的控制,例如:文件大小、類型等,但是,一不小心就會被黑客鑽了空子,上傳了木馬程序。

下面將利用Nginx配置禁止訪問上傳資源目錄下的PHP、Shell、Perl、Python程序文件,這樣用戶即使上傳了木馬文件也沒法執行,從而加強了網站的安全。

範例1:配置Nginx,禁止解析指定目錄下的指定程序。

location ~ ^/images/.*\.(php|php5|sh|pl|py)$
{
	deny all;
}
location ~ ^/static/.*\.(php|php5|sh|pl|py)$
{
	deny all;
}
location ~* ^/data/(attachment|avatar)/.*\.(php|php5)$
{
	deny all;
}

對上述目錄的限制必須寫在Nginx處理PHP服務配置的前面。

deny all; 導致瀏覽器頁面顯示 403 Forbidden。狀態碼403。

範例2:Nginx下配置禁止訪問*.txt和*.doc文件。

location ~* \.(txt|doc)$ {
	if (-f $request_filename) {
		root /data/www/www;
		#rewrite ......可以重定向到某個URL
		break;
	}
}
location ~* \.(txt|doc)$ {
	root /data/www/www;
	deny all;
}

{未換行,則{前面要有空格。

禁止訪問指定目錄下的所有文件和目錄

範例1:配置禁止訪問指定的單個或多個目錄。

禁止訪問單個目錄的命令如下:

location ~ ^/(static)/ {
	deny all;
}
location ~ ^/static {
	deny all;
}

禁止訪問多個目錄的命令如下:

location ~ ^/(static|js) {
	deny all;
}

範例2:禁止訪問目錄並返回指定的HTTP狀態碼,命令如下:

server {
	listen       80;
	server_name  www.test.org;
	root   /data0/www/test;
	index  index.html index.htm;
	access_log  /app/logs/www_access.log  commonlog;
	location /admin/ { return 404; }
	location /templates/ { return 403; }
}

作用:禁止訪問目錄下的指定文件,或者禁止訪問指定目錄下的所有內容。

最佳應用場景:對於集羣的共享存儲,一般是存放靜態資源文件,所以可禁止執行指定擴展名的程序,例:.php、.sh、.pl、.py。

限制網站來源IP訪問

下面介紹如何使用ngx_http_access_module限制網站來源IP訪問。
案例環境:phpmyadmin數據庫的Web客戶端,內部開發人員用的。
範例1:禁止某目錄讓外界訪問,但允許某IP訪問該目錄,且支持PHP解析,命令如下:

location ~ ^/phpmyadmin/ {
	allow 202.111.12.211; 
	deny all;
}
location ~ .*\.(php|php5)$ {
	fastcgi_pass  127.0.0.1:9000;
	fastcgi_index index.php;
	include fastcgi_params;
	fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

範例2:限制指定IP或IP段訪問,命令如下:

location / {
	deny 192.168.1.1;
	allow 192.168.1.0/24;
	allow 10.1.1.0/16;
	deny all;
}

參考:http://nginx.org/en/docs/http/ngx_http_access_module.html 。

企業問題案例:Nginx做反向代理的時候可以限制客戶端IP嗎?
解答:可以,具體方法如下。
方法1:使用if來控制,命令如下:

if ( $remote_addr = 192.168.55.1 ) {
	return 403;
}
if ( $remote_addr = 218.247.17.130 ) {  #這句話失敗了
	set $allow_access_root 'true';
}

參考:http://nginx.org/en/docs/varindex.html

方法2:利用deny和allow只允許IP訪問,命令如下:

location / {
	allow 192.168.55.2;
	deny all;
}

方法3:只拒絕某些IP訪問,命令如下:

location / {
	deny 192.168.55.1;
	allow all;
}

注意事項:

  • deny一定要加一個IP,否則會直接跳轉到403,不再往下執行了,如果403默認頁是在同一域名下,會造成死循環訪問。
  • 對於allow的IP段,從允許訪問的段位從小到大排列,如127.0.0.0/24的下面才能是10.10.0.0/16,其中:
    • 24表示子網掩碼:255.255.255.0
    • 16表示子網掩碼:255.255.0.0
  • 8表示子網掩碼:255.0.0.0
  • 以deny all; 結尾,表示除了上面允許的,其他的都禁止。如:
    deny 192.168.1.1;
    allow 127.0.0.0/24;
    allow 192.168.0.0/16;
    allow 10.10.0.0/16;
    deny all;

配置Nginx,禁止非法域名解析訪問企業網站

這段內容配置失敗。

問題:Nginx如何防止用戶IP訪問網站(惡意域名解析,也相當於是直接IP訪問企業網站)?
方法1:讓使用IP訪問網站的用戶,或者惡意解析域名的用戶,收到501錯誤,命令如下:

server {
	listen 80 default_server;
	server_name _;
	return 501;
}

說明:直接報501錯誤,從用戶體驗上不是很好。

方法2:通過301跳轉到主頁,命令如下:

server {
	listen 80 default_server;
	server_name _;
	rewrite ^(.*) http://blog.etiantian.org/$1 permanent;
}

方法3:發現某域名惡意解析到公司的服務器IP,在server標籤裏添加以下代碼即可,若有多個server則要多處添加。

if ($host !~ ^www/.eduoldboy/.com$) {
	rewrite ^(.*)  http://www.eduoldboy.com$1 permanent;
}

上面代碼的意思是如果header信息的host主機名字段非 www.eduoldboy.com,就301跳轉到 www.eduoldboy.com

參考文獻

[1] Nginx官網[DB|OL]. http://nginx.org/en/docs/ .
[2] 老男孩. 跟老男孩學Linux運維:Web集羣實戰[M]. 機械工業出版社,2016-03-01.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章