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/emailAddress=1633307645@qq.com
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.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值