apache、nginx 遇到的使用功能总结

495 阅读8分钟

【相关文章】

SELinux 了解及CentOS7 中 semanage命令的安装

Linux semanage 命令用法详解-Linux命令大全(手册)

Linux惊群效应详解(最详细的了吧)


文章记录

apache和tomcat的区别tomcat 与 nginx,apache的区别是什么?

apache、Nginx静态资源服务器,本身不支持生成动态页面,但它们可
以通过其他模块来支持(例如通过Shell、PHP、Python脚本程序来动态生成内容)。

apache 要使用java的话,你需要tomcat在apache后台支撑,将java请
求由apache转发给tomcat处理。

apache是web服务器,Tomcat是应用(java)服务器,它只是一个servlet(jsp也翻译成servlet)容器,
可以认为是apache的扩展,但是可以独立于apache运行。 

apache

如何在CentOS 7上安装Apache

# sudo yum install httpd

安装完成后,启用并启动Apache服务:
# systemctl enable httpd
# systemctl start httpd

如果您正在运行防火墙,则还需要打开HTTP和HTTPS端口80和443:
# firewall-cmd --permanent --zone=public --add-service=http
# firewall-cmd --permanent --zone=public --add-service=https
# firewall-cmd --reload

我们可以通过以下方式检查Apache服务的状态和版本:
# systemctl status httpd
# httpd -v

使用 Apache 服务部署静态网站

1.httpd 服务程序的主要配置文件及存放位置:
服务目录 /etc/httpd
主配置文件 /etc/httpd/conf/httpd.conf
网站数据目录 /var/www/html
访问日志 /var/log/httpd/access_log
错误日志 /vat/log/httpd/error_log

2.主配置文件 (见本文)

3.semanage命令 (重要 见本文及上面相关文章)

4.个人用户主页功能 (了解)

5.身份验证访问(了解)

6.虚拟主机功能(重要)
6.1 基于 IP 地址
6.2 基于主机域名
6.3 基于端口号

7.Apache的访问控制(了解)

Nginx


安装

centos7下安装nginx

runoob-Nginx 安装配置

一、安装编译工具及库文件

yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

二、安装 PCRE(让 Nginx 支持 Rewrite 功能)

#下载最新版本的,注意不要用pcre2
cd /usr/local/src/
wget https://nchc.dl.sourceforge.net/project/pcre/pcre/8.43/pcre-8.43.tar.gz
tar -xvf pcre-8.43.tar.gz
cd pcre-8.43
#安装编译
./configure
make && make install
#查看pcre版本
pcre-config --version

三、安装nginx

#下载
cd /usr/local/src/
wget https://nginx.org/download/nginx-1.16.1.tar.gz
tar -xvf nginx-1.16.1.tar.gz
cd nginx-1.16.1
#安装前可以进行-修改nginx软件名优化,起到安全作用。优化方法见下面的Nginx优化章节。
#编译安装
./configure --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.43
make && make install
#查看版本
/usr/local/webserver/nginx/sbin/nginx -v

四、Nginx 配置

  • 创建 Nginx 运行使用的用户 www:

    groupadd www 
    useradd -g www www
    
  • 配置nginx.conf 见下面

  • 启动Nginx

    
    /usr/local/webserver/nginx/sbin/nginx -t                   # 检查配置文件nginx.conf的正确性命令
    /usr/local/webserver/nginx/sbin/nginx                      # 启动
    /usr/local/webserver/nginx/sbin/nginx -s reload            # 重新载入配置文件
    /usr/local/webserver/nginx/sbin/nginx -s reopen            # 重启 Nginx
    /usr/local/webserver/nginx/sbin/nginx -s stop              # 停止 Nginx
    

五、Nginx配置开机自启动

centos7.x设置nginx开机自启动

# cd /lib/systemd/system/
# vi nginx.service

[Unit]
Description=nginx service
After=network.target 

[Service] 
Type=forking 
ExecStart=/usr/local/webserver/nginx/sbin/nginx
ExecReload=/usr/local/webserver/nginx/sbin/nginx -s reload
ExecStop=/usr/local/webserver/nginx/sbin/nginx -s quit
PrivateTmp=true 

[Install] 
WantedBy=multi-user.target

# systemctl enable nginx

配置

配置讲解:

1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。

5、location块:配置请求的路由,以及各种页面的处理情况。

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
   accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on 何为惊群?见相关文章
   multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
   #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
   worker_connections  1024;    #最大连接数,默认为512
}
http {
   include       mime.types;   #文件扩展名与文件类型映射表
   default_type  application/octet-stream; #默认文件类型,默认为text/plain
   #access_log off; #取消服务日志    
   log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
   access_log log/access.log myFormat;  #combined为日志格式的默认值
   sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
   sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
   keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

   upstream mysvr {   
     server 127.0.0.1:7878;
     server 192.168.10.121:3333 backup;  #热备
   }
   error_page 404 https://www.baidu.com; #错误页
   server {
       keepalive_requests 120; #单连接请求上限次数。
       listen       4545;   #监听端口
       server_name  127.0.0.1;   #监听地址       
       location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
          #root path;  #根目录
          #index vv.txt;  #设置默认页
          proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
          deny 127.0.0.1;  #拒绝的ip
          allow 172.18.5.54; #允许的ip           
       } 
   }
}

log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer

 1.$remote_addr 与 $http_x_forwarded_for 用以记录客户端的ip地址;
 2.$remote_user :用来记录客户端用户名称;
 3.$time_local : 用来记录访问时间与时区;
 4.$request : 用来记录请求的url与http协议;
 5.$status : 用来记录请求状态;成功是200;
 6.$body_bytes_s ent :记录发送给客户端文件主体内容大小;
 7.$http_referer :用来记录从那个页面链接访问过来的;
 8.$http_user_agent :记录客户端浏览器的相关信息;

nginx配置模板详解:



user  www www;
worker_processes  2; #定义了nginx对外提供web服务时的worker进程数。最优值取决于许多因素,
#包括(但不限于)CPU核的数量、存储数据的硬盘数量及负载模式。
#不能确定的时候,将其设置为可用的CPU内核数将是一个好的开始(设置为“auto”将尝试自动检测它)。
worker_cpu_affinity 0101 1010; #https://blog.51cto.com/13673885/2299766
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志级别

#pid        logs/nginx.pid;
pid /usr/local/webserver/nginx/nginx.pid;

#配置Nginx worker进程最大打开文件数
#更改worker进程的最大打开文件数限制。如果没设置的话,这个值为操作系统的限制。
#设置后你的操作系统和Nginx可以处理比“ulimit -a”更多的文件,所以把这个值设高,这样nginx就不会有“too many open files”问题了。
#worker_rlimit_nofile 65535; 

events {
   use epoll;
   #单个进程允许的客户端最大连接数
   #设置可由一个worker进程同时打开的最大连接数。如果设置了上面提到的worker_rlimit_nofile,我们可以将这个值设得很高。
   worker_connections  20480; 
   #告诉nginx收到一个新连接通知后接受尽可能多的连接
   multi_accept on; 
}


http {
   include       mime.types;
   default_type  application/octet-stream;

   log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

   access_log  logs/access.log  main;

#nginx优化----------------------
   #可以让sendfile()发挥作用。sendfile()可以在磁盘和TCP socket之间互相拷贝数据(或任意两个文件描述符)。
   #Pre-sendfile是传送数据之前在用户空间申请数据缓冲区。
   #之后用read()将数据从文件拷贝到这个缓冲区,write()将缓冲区数据写入网络。
   #sendfile()是立即将数据从磁盘读到OS缓存。因为这种拷贝是在内核完成的,
   #sendfile()要比组合read()和write()以及打开关闭丢弃缓冲更加有效(更多有关于sendfile)。
   sendfile        on;
   #tcp_nopush     on; 
   #tcp_nopush on表示将数据积攒到一定的量再进行传输
   #tcp_nodelay on表示将数据信息进行快速传输

   #keepalive_timeout  0;
   keepalive_timeout  65;
   
   #读取客户端请求头数据的超时时间 默认秒 默认60秒
   client_header_timeout 15;
   
   #读取客户端请求主体的超时时间 默认秒 默认60秒
   client_body_timeout 15;
   
   #响应客户端的超时时间 默认秒 默认60秒
   send_timeout 25;

   #上传文件的大小限制  默认1m
   client_max_body_size 8m;

   #gzip  on;
   #使用gzip压缩
   #为指定的客户端禁用gzip功能。我们设置成IE6或者更低版本以使我们的方案能够广泛兼容。
   gzip_disable "msie6";
   #gzip_static 告诉nginx在压缩资源之前,先查找是否有预先gzip处理过的资源。
   #这要求你预先压缩你的文件(在这个例子中被注释掉了),从而允许你使用最高压缩比,
   #这样nginx就不用再压缩这些文件了(想要更详尽的gzip_static的信息,请点击这里)。
   #gzip_static on;
   gzip on;
   gzip_min_length 1k;
   gzip_buffers 4 32k;
   gzip_http_version 1.1;
   #设置数据的压缩等级。这个等级可以是1-9之间的任意数值,9是最慢但是压缩比最大的。我们设置为4,这是一个比较折中的设置。
   gzip_comp_level 2;
   #设置需要压缩的数据格式。上面例子中已经有一些了,你也可以再添加更多的格式
   gzip_types text/css text/xml application/json application/javascript text/plain application/x-javascript application/xml;
   gzip_vary on;
   
   #nginx与php之间FastCGI 相关参数调优
   #时间超时设定
   #fastcgi_connect_timeout 240;
   #fastcgi_send_timeout 240;
   #fastcgi_read_timeout 240;
   #缓冲/缓存设置
   #fastcgi_buffer_size 64k;
   #fastcgi_buffers 4 64k;
   #fastcgi_busy_buffers_size 128k;
   #fastcgi_temp_file_write_size 128k;
   #fastcgi_temp_path /data/ngx_fcgi_tmp;
   #fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
   
   #缓存服务器静态文件
   proxy_connect_timeout 10;
   proxy_read_timeout 180;
   proxy_send_timeout 5;
   proxy_buffer_size 16k;
   proxy_buffers 4 64k;
   proxy_busy_buffers_size 192k;
   proxy_temp_file_write_size 192k;
   proxy_temp_path /tmp/temp_dir;
   proxy_cache_path /home/cache levels=1:2 keys_zone=cache_one:100m inactive=1d max_size=10g;


   server {
       listen       80; #监听端口
       server_name  localhost; #域名

       #charset koi8-r;
   	charset utf-8;

       #access_log  logs/host.access.log  main;

       location / {
           root   html;
           index  index.html index.htm;
       }
   	
   	#方式一(二选一):目前看用于测试,或者用于转发到其他服务器上。当前可用方式二
   	#要缓存文件的后缀,可以在以下设置。此配置为访问90端口进行缓存,
   	location ~ .*\.(gif|jpg|png|bmp|swf|css|js)(.*) {
   		 proxy_pass http://localhost:90;
   		 proxy_redirect off;
   		 proxy_set_header Host $host;
   		 proxy_cache cache_one;
   		 proxy_cache_valid 200 302 24h;
   		 proxy_cache_valid 301 30d;
   		 proxy_cache_valid any 5m;
   		 expires 90d;
   		 #add_header wall  "hey!guys!give me a star."; #是用于在报头设置自定义的信息,如果缓存有效的话,那么静态资源返回的报头,一定会带上这个信息
   	}
   	# 无nginx缓存的blog端口
   	server {
   		listen  90;
   		server_name localhost;
   		root /home/safiri/;

   		location / {

   		}
   	}
   	
   	#方式二(二选一):
   	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
   		expires 90d;
   		root html/www;#根据项目实际配置
   	}
   	location ~ .*\.(js|css)?$ {
   		expires 30d;
   		root html/www;#根据项目实际配置
   	}

       #error_page  404              /404.html;

       # redirect server error pages to the static page /50x.html
       #
       error_page   500 502 503 504  /50x.html;
       location = /50x.html {
           root   html;
       }

       # proxy the PHP scripts to Apache listening on 127.0.0.1:80
       #
       #location ~ \.php$ {
       #    proxy_pass   http://127.0.0.1;
       #}

       # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
       #
       #location ~ \.php$ {
       #    root           html;
       #    fastcgi_pass   127.0.0.1:9000;
       #    fastcgi_index  index.php;
       #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
       #    include        fastcgi_params;
       #}

       # deny access to .htaccess files, if Apache's document root
       # concurs with nginx's one
       #
       #location ~ /\.ht {
       #    deny  all;
       #}
   }
   
   

   # another virtual host using mix of IP-, name-, and port-based configuration
   #
   #server {
   #    listen       8000;
   #    listen       somename:8080;
   #    server_name  somename  alias  another.alias;

   #    location / {
   #        root   html;
   #        index  index.html index.htm;
   #    }
   #}


   # HTTPS server
   #
   #server {
   #    listen       443 ssl;
   #    server_name  localhost;

   #    ssl_certificate      cert.pem;
   #    ssl_certificate_key  cert.key;

   #    ssl_session_cache    shared:SSL:1m;
   #    ssl_session_timeout  5m;

   #    ssl_ciphers  HIGH:!aNULL:!MD5;
   #    ssl_prefer_server_ciphers  on;

   #    location / {
   #        root   html;
   #        index  index.html index.htm;
   #    }
   #}
   
   #隐藏版本号
   server_tokens off;
}


使用nginx缓存服务器上的静态文件 重要

具体配置见下节

http层设置
proxy_connect_timeout 服务器连接的超时时间
proxy_read_timeout 连接成功后,等候后端服务器响应时间
proxy_send_timeout 后端服务器数据回传时间
proxy_buffer_size 缓冲区的大小
proxy_buffers 每个连接设置缓冲区的数量为number,每块缓冲区的大小为size
proxy_busy_buffers_size 开启缓冲响应的功能以后,在没有读到全部响应的情况下,写缓冲到达一定大小时,nginx一定会向客户端发送响应,直到缓冲小于此值。
proxy_temp_file_write_size 设置nginx每次写数据到临时文件的size(大小)限制
proxy_temp_path 从后端服务器接收的临时文件的存放路径
proxy_cache_path 设置缓存的路径和其他参数。被缓存的数据如果在inactive参数(当前为1天)指定的时间内未被访问,就会被从缓存中移除

server层设置,反向缓存代理服务器
proxy_pass nginx缓存里拿不到资源,向该地址转发请求,拿到新的资源,并进行缓存
proxy_redirect 设置后端服务器“Location”响应头和“Refresh”响应头的替换文本
proxy_set_header 允许重新定义或者添加发往后端服务器的请求头
proxy_cache 指定用于页面缓存的共享内存,对应http层设置的keys_zone
proxy_cache_valid 为不同的响应状态码设置不同的缓存时间
expires 缓存时间

自己用的配置


user  www www;
worker_processes  2;
worker_cpu_affinity 0101 1010;
error_log /usr/local/webserver/nginx/logs/nginx_error.log crit;
pid /usr/local/webserver/nginx/nginx.pid;

worker_rlimit_nofile 65535;

events {
	use epoll;
    worker_connections  20480; 
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    sendfile        on;
	
    keepalive_timeout  65;
    client_header_timeout 15;
    client_body_timeout 15;
    send_timeout 25;
    client_max_body_size 8m;

    gzip on;
    gzip_disable "msie6";
    gzip_min_length 1k;
    gzip_buffers 4 32k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/css text/xml application/json application/javascript text/plain application/x-javascript application/xml;
    gzip_vary on;
	
	#nginx与php之间FastCGI 相关参数调优
    #时间超时设定
    #fastcgi_connect_timeout 240;
    #fastcgi_send_timeout 240;
    #fastcgi_read_timeout 240;
    #缓冲/缓存设置
    #fastcgi_buffer_size 64k;
    #fastcgi_buffers 4 64k;
    #fastcgi_busy_buffers_size 128k;
    #fastcgi_temp_file_write_size 128k;
    #fastcgi_temp_path /data/ngx_fcgi_tmp;
    #fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
	
	
	#缓存服务器静态文件
	proxy_connect_timeout 10;
	proxy_read_timeout 180;
	proxy_send_timeout 5;
	proxy_buffer_size 16k;
	proxy_buffers 4 64k;
	proxy_busy_buffers_size 192k;
	proxy_temp_file_write_size 192k;
	proxy_temp_path /tmp/temp_dir;
	proxy_cache_path /home/cache levels=1:2 keys_zone=cache_one:100m inactive=1d max_size=10g;

	#虚拟主机
	include /usr/local/webserver/nginx/conf/image.conf; #根据项目实际配置
    
	#隐藏版本号
    server_tokens off;
}

/usr/local/webserver/nginx/conf/image.conf :

server {
        listen       80; #监听端口
        server_name  localhost; #域名

		charset utf-8;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
		
		#隐藏版本号
		server_tokens on;
 
		#客户端对静态内容缓存 添加的
		location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
			expires 90d;#根据项目实际配置
			root /home/safiri/;#根据项目实际配置
			#add_header wall  "test cash success.";
		}
		location ~ .*\.(js|css)?$ {
			expires 30d;#根据项目实际配置
			root /home/safiri/;#根据项目实际配置
		}
		
        #error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

Nginx & Openresty 重要

Nginx优化

Nginx优化 重要

Nginx配置性能优化

Nginx配置性能优化

  • 隐藏nginx版本信息优化 --OK

  • 修改nginx软件名优化 --未实验 修改NGINX版本并伪装任意WEB SERVER

  • nginx优化worker进程数量信息 --OK

    worker_processes auto; 写这个就可以了

  • 优化nginx服务对CPU亲和力worker_cpu_affinity --OK

  • nginx事件处理模型优化use epoll; --OK

  • 优化worker进程连接数量能力worker_connections --OK

  • worker进程最大打开文件数worker_rlimit_nofile --OK

  • 优化nginx服务数据高效传输模式 --OK

    利用sendfile on开启高效传输模式

    tcp_nopush on表示将数据积攒到一定的量再进行传输

    tcp_nodelay on表示将数据信息进行快速传输

  • 优化nginx服务超时信息 --OK

  • 优化上传文件大小的限制client_max_body_size 8m; --OK

    根据业务需求调整上传文件大小限制

  • 优化nginx服务与FastCGI连接缓存与缓冲信息 -- 未实验

    PHP相关?

  • 配置Nginx gzip压缩 实现性能优化 --OK

    不是所有资源都要压缩,图片、视频、小于1k的等文件尽量不要压缩

  • expires缓存实现性能优化 -- OK

  • 日志优化 --未实验

    进行日志文件轮询切割(系统自带的logrotate切割nginx日志) -- 未实验

  • 站点目录及文件URL访问控制 --未实验

  • 图片及目录防盗链 --未实验

  • Nginx错误页面的优雅显示 --未实验

  • 站点目录文件及目录权限优化 --未实验

  • 防爬虫 --未实验

  • 利用nginx限制HTTP的请求方法--防止脚本被上传至服务器运行该脚本对系统的破坏 --未实验

  • 使用普通用户启动nginx(监牢模式) --未实验