码迷,mamicode.com
首页 > 其他好文 > 详细

一:Nginx初级介绍

时间:2019-12-21 22:17:59      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:并且   配置   web服务   请求头   icon   logs   key   address   重启nginx   

一:Nginx基础概述

1.Nginx简述

  • Nginx是一个开源且高性能、可靠的Http Web服务、代理服务。

  • 开源: 直接获取源代码

  • 高性能: 支持海量并发

  • 可靠: 服务稳定

2.为什么选择Nginx服务

1.1 Nginx非常轻量

  • 功能模块少 (源代码仅保留http与核心模块代码,其余不够核心代码会作为插件来安装)

  • 代码模块化 (易读,便于二次开发,对于开发人员非常友好)

1.2 互联网公司都选择Nginx

  • Nginx技术成熟,具备的功能是企业最常使用而且最需要的

  • 适合当前主流架构趋势, 微服务、云架构、中间层

  • 统一技术栈, 降低维护成本, 降低技术更新成本。

1.3 Nginx采用Epool网络模型,Apache采用Select模型

  • Select: 当用户发起一次请求,select模型就会进行一次遍历扫描,从而导致性能低下。

  • Epool: 当用户发起请求,epool模型会直接进行处理,效率高效,并无连接限制。

二:Nginx部署安装

1.安装方式

1.1 源码编译=>Nginx (1.版本随意 2.安装复杂 3.升级繁琐 4.规范 5.便于管理)

1)解压:
[root@web01 ~]# tar xf nginx-1.16.0.tar.gz
创建www用户
groupadd www -g 666
useradd www -u 666 -g 666 -s /sbin/nologin -M

2)生成  ./configure --prefix=/application/nginx-1.16.0 --user=www --group=www --with-http_ssl_module \        #激活ssl模块
--with-http_stub_status_module  #激活状态模块
--with-stream                   #激活负载均衡的stream模块

3)编译
make

4)安装
make install

1.2 epel仓库=>Nginx (1.版本较低 2.安装简单 3.配置不易读)

1.3 官方仓库=>Nginx (1.版本较新 2.安装简单 3.配置易读)

2.如何升级nginx或者添加功能模块

#设置软链接
ln -s /application/nginx-1.16.0 /application/nginx

#升级版本并添加模块
 ./configure --prefix=/application/nginx-1.16.1 --user=www --group=www --with-http_ssl_module --with-http_stub_status_module --with-stream --with-http_mp4_module    #增加的新模块

make && make install 

[root@web01 nginx-1.16.1]# ll /application/
total 0
lrwxrwxrwx 1 root root 26 Sep  3 16:29 nginx -> /application/nginx-1.16.0/
drwxr-xr-x 6 root root 54 Sep  3 16:28 nginx-1.16.0
drwxr-xr-x 6 root root 54 Sep  3 16:38 nginx-1.16.1

#重新软链接
rm -f /application/nginx && ln -s /application/nginx-1.17.0 /application/nginx
--------------------------------------------------------------------------------------------------
#仅添加模块
 ./configure --prefix=/application/nginx_new-1.16.0 \      #生成新的文件名即可
--user=www --group=www --with-http_ssl_module --with-http_stub_status_module --with-stream --with-http_mp4_module      #增加的新模块

make && make install 
#重新软链接
rm -f /application/nginx && ln -s /application/nginx_new-1.16.0 /application/nginx

--------------------------------------------------------------------------------------------
#回滚之前的版本
报错点
#当启动完nginx后,查看log下面的文件,cat查看nginx.pid可以看到进程pid
[root@web01 ~]# ll /application/nginx/logs/
total 4
-rw-r--r-- 1 root root 0 Sep  3 16:40 access.log
-rw-r--r-- 1 root root 0 Sep  3 16:40 error.log
-rw-r--r-- 1 root root 6 Sep  3 16:40 nginx.pid
[root@web01 ~]# cat /application/nginx/logs/nginx.pid 
13095
[root@web01 ~]# ps -ef|grep nginx
root      13095      1  0 16:40 ?        00:00:00 nginx: master process /application/nginx/sbin/nginx
www       13096  13095  0 16:40 ?        00:00:00 nginx: worker process
root      13102   6988  0 16:41 pts/0    00:00:00 grep --color=auto nginx
1.做完软链接,因需求变更进行回滚,回滚倒1.16.1
[root@web01 ~]# rm -rf /application/nginx && ln -s /application/nginx-1.16.1/ /application/nginx
[root@web01 ~]# ll /application/
total 0
lrwxrwxrwx  1 root root  26 Sep  3 16:44 nginx -> /application/nginx-1.16.1/
drwxr-xr-x 11 root root 151 Sep  3 16:40 nginx-1.16.0
drwxr-xr-x  6 root root  54 Sep  3 16:38 nginx-1.16.1
2.此时重新加载配置文件会报错
[root@web01 ~]# /application/nginx/sbin/nginx -s reload
nginx: [error] open() "/application/nginx-1.16.1/logs/nginx.pid" failed (2: No such file or directory)

3.此时会发现回滚到之前版本后,里面没有nginx.pid,说明现在进程用的还是之前版本的pid
    [root@web01 ~]# ll /application/nginx/logs/
    total 4
    -rw-r--r-- 1 root root   0 Sep  3 16:46 access.log
    -rw-r--r-- 1 root root 530 Sep  3 16:46 error.log
    [root@web01 ~]# ll /application/nginx-1.16.0/logs/        #现在进程用的还是之前版本1.16.0的pid
    total 4
    -rw-r--r-- 1 root root 0 Sep  3 16:40 access.log
    -rw-r--r-- 1 root root 0 Sep  3 16:40 error.log
    -rw-r--r-- 1 root root 6 Sep  3 16:40 nginx.pid
4.如何操作? 只要将之前nginx的pid文件移动到现在回滚的版本内,再次加载OK,这样就不会影响用户体验了
    [root@web01 ~]#  mv /application/nginx-1.16.0/logs/nginx.pid /application/nginx-1.16.1/logs/
    [root@web01 ~]# /application/nginx/sbin/nginx -s reload

3.验证nginx是否启动

1.1 systemctl status nginx

[root@web01 ~]# systemctl status nginx
nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2019-09-03 13:51:06 CST; 35min ago
     Docs: http://nginx.org/en/docs/
  Process: 7174 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 7175 (nginx)
   CGroup: /system.slice/nginx.service
           ├─7175 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─7176 nginx: worker process

Sep 03 13:51:06 web01 systemd[1]: Starting nginx - high performance web server...
Sep 03 13:51:06 web01 systemd[1]: PID file /var/run/nginx.pid not readable (yet?) after start.
Sep 03 13:51:06 web01 systemd[1]: Started nginx - high performance web server.
Hint: Some lines were ellipsized, use -l to show in full.

1.2 netstat -lntup

[root@web01 ~]# netstat -lntup
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      7175/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6718/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      6858/master         
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd           
tcp6       0      0 :::22                   :::*                    LISTEN      6718/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      6858/master         
udp        0      0 0.0.0.0:111             0.0.0.0:*                           1/systemd           
udp        0      0 0.0.0.0:740             0.0.0.0:*                           5709/rpcbind        
udp6       0      0 :::111                  :::*                                1/systemd           
udp6       0      0 :::740                  :::*                                5709/rpcbind        

1.3 ps -ef|grep nginx

备注:如果发现nginx启动发错,停止nginx服务后ps查看还有nginx的进程,可以top看下是否有僵尸进程,如果没有,那也快 变成僵尸进程了。需要kill -9杀死僵尸进程

补充:

[root@web01 ~]# pidof nginx

7176 7175

[root@web01 ~]# ps -ef|grep nginx
root       7175      1  0 13:51 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx      7176   7175  0 13:51 ?        00:00:00 nginx: worker process
root       7203   6988  0 14:28 pts/0    00:00:00 grep --color=auto nginx

1.4 curl 10.0.0.7

[root@web01 ~]# curl 10.0.0.7
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;

1.5 nginx -v

[root@web01 ~]# nginx -v 
nginx version: nginx/1.16.1  

1.6 nginx -V

[root@web01 ~]# nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
#路径
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx 
官方默认编译模块
--with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

4.将源码安装的nginx用systemd管理

#在system加入nginx的服务
[root@web01 system]#vim /etc/systemd/system/nginx.service 

[Unit]

Description=nginx server daemon

Documentation=man:nginx(8)

After=network.target

[Service]

Type=forking
#指定nginx的pid
PIDFile=/application/nginx/logs/nginx.pid     
#路径一定要正确
ExecStart=/application/nginx/sbin/nginx -c /application/nginx/conf/nginx.conf

ExecReload=/application/nginx/sbin/nginx -s reload
#或者ExecReload=/bin/kill -s HUP $MAINPID                     #因为重新加载等服务都是由kill发信号的
ExecStop=/application/nginx/sbin/nginx -s quit
#或者ExecStop=/bin/kill -s TERM $MAINPID

PrivateTmp=true

[Install]

WantedBy=multi-user.target

三:Nginx相关配置文件

  • 为了让大家更清晰的了解Nginx软件的全貌,可使用rpm -ql nginx查看整体的目录结构及对应的功能,如下表格整理了Nginx比较重要的配置文件

1.Nginx主配置文件

  • 主配置文件的配置全局都生效
路径 类型 作用
/etc/nginx/nginx.conf 配置文件 nginx主配置文件
/etc/nginx/conf.d/default.conf 配置文件 默认网站配置文件

2.Nginx代理相关参数文件

路径 类型 作用
/etc/nginx/fastcgi_params 配置文件 Fastcgi代理配置文件
/etc/nginx/scgi_params 配置文件 scgi代理配置文件
/etc/nginx/uwsgi_params 配置文件 uwsgi代理配置文件

3.Nginx编码相关配置文件

路径 类型 作用
/etc/nginx/win-utf 配置文件 Nginx编码转换映射文件
/etc/nginx/koi-utf 配置文件 Nginx编码转换映射文件
/etc/nginx/koi-win 配置文件 Nginx编码转换映射文件
/etc/nginx/mime.types 配置文件 Content-Type与扩展名

4.Nginx管理相关命令

路径 类型 作用
/usr/sbin/nginx 命令 Nginx命令行管理终端工具
/usr/sbin/nginx-debug 命令 Nginx命令行与终端调试工具

5.Nginx日志相关目录与文件

路径 类型 作用
/var/log/nginx 目录 Nginx默认存放日志目录
/etc/logrotate.d/nginx 配置文件 Nginx默认的日志切割

四:Nginx配置文件详解

Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组织的。一般,每个区块以一对大括号{}来表示开始与结束。

Nginx主配置文件整体分为三块进行学习,分别是CoreModule(核心模块)EventModule(事件驱动模块)HttpCoreModule(http内核模块)

vim/etc/nginx/nginx.conf
1.CoreModule(核心模块)

user  nginx;            #用户
worker_processes  1;    #worker进程

error_log  /var/log/nginx/error.log warn;              #错误日志
pid        /var/run/nginx.pid;                         #pid存放的路径

---------------------------------------------------------------------------------
2.EventModule(事件驱动模块)

events {
    worker_connections  1024;       #worker进程最大支持连接数
}

---------------------------------------------------------------------------------
3.HttpCoreModule(http内核模块)
#http层开始
http {
    include       /etc/nginx/mime.types;            #记录nginx可加载的所有文件类型
    default_type  application/octet-stream;         ##默认情况下,nginx会将请求的内容下载

 log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ' #nginx内置的变量
                      '$status $body_bytes_sent "$http_referer" ' #main是给这些变量起的名
                      '"$http_user_agent" "$http_x_forwarded_for"';

   access_log  /var/log/nginx/access.log  main;            #main是给这些变量起的名
#可以在全局配置里自定义log的格式的变量,比如在网站配置文件中的日志格式不需要加时间:
#可以在全局配置里增加
   
     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '   
                      '$status $body_bytes_sent "$http_referer" '              
                      '"$http_user_agent" "$http_x_forwarded_for"';
     log_format  abc  '$remote_addr -  "$request" ' 
                      '$status $body_bytes_sent "$http_referer" '               
                      '"$http_user_agent" "$http_x_forwarded_for"';
#在网站配置文件调用
access_log  /var/log/nginx/access.log  abc;

    sendfile        on;       #高效文件传输
    #tcp_nopush     on;       #搭配sendfile使用 
#长连接超时时间,65内不对页面进行操作,将断开tcp连接,需再次请求
    keepalive_timeout  65;
#开启压缩
    #gzip  on;
#包含哪些配置文件
    include /etc/nginx/conf.d/*.conf;
}     #http层结束
#虚拟主机
server {
#监听的端口
    listen       80;
#域名, _; localhost;
    server_name  localhost;
#location匹配规则
    location / {
#root:定义站点目录的变量其实就是:root=/usr/share/nginx/html;
        root   /usr/share/nginx/html;
#指定索引页面(默认主页)
        index  index.html index.htm;
    }

备注:yum安装的nginx.conf和源码安装的nginx.conf里面的配置文件有区别,为什么?

:因为yum官方安装的/nginx/nginx.conf+nginx/conf.d/default.conf=源码安装的nginx.conf,说明可以配置多个server虚拟主机

## yum:

## [root@web02 ~]# vim /etc/nginx/nginx.conf 

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

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

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

?    access_log  /var/log/nginx/access.log  main;

?    sendfile        on;
?    #tcp_nopush     on;

?    keepalive_timeout  65;

?    #gzip  on;

?    include /etc/nginx/conf.d/*.conf;

## }

## [root@web02 ~]# vim /etc/nginx/conf.d/default.conf 

#虚拟主机
server {
#监听的端口
    listen       80;
#域名, _; localhost;
    server_name  localhost;

?    #charset koi8-r;
?    #access_log  /var/log/nginx/host.access.log  main;
#location匹配规则
?    location / {
#root:定义站点目录的变量其实就是:root=/usr/share/nginx/html;
?        root   /usr/share/nginx/html;
#指定索引页面(默认主页)
?        index  index.html index.htm;
?    }

?    #error_page  404              /404.html;

# redirect server error pages to the static page /50x.html

?    #
?    error_page   500 502 503 504  /50x.html;
?    location = /50x.html {
?        root   /usr/share/nginx/html;
?    }

# proxy the PHP scripts to Apache listening on 127.0.0.1:80

?    #
?    #location ~ \.php$ {

# proxy_pass   http://127.0.0.1;

?    #}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

?    #
?    #location ~ \.php$ {

# root           html;

# fastcgi_pass   127.0.0.1:9000;

# fastcgi_index  index.php;

# fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

# include        fastcgi_params;

?    #}

# deny access to .htaccess files, if Apache's document root

# concurs with nginx's one

?    #
?    #location ~ /\.ht {

# deny  all;

?    #}
}

------

源码安装的nginx.conf

## [root@web01 conf]# cat nginx.conf

#user  nobody;
worker_processes  1;

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

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

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;
?    #tcp_nopush     on;

?    #keepalive_timeout  0;
?    keepalive_timeout  65;

?    #gzip  on;

?    server {
?        listen       80;
?        server_name  localhost;

?        #charset koi8-r;

?        #access_log  logs/host.access.log  main;

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

?        #error_page  404              /404.html;

# redirect server error pages to the static page /50x.html

?        #
?        error_page   500 502 503 504  /50x.html;
?        location = /50x.html {
?            root   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;

# }

?    #}

}

补充1:/etc/nginx/mime.types; #文件资源类型的种类

[root@web01 conf]# vim  mime.types
#为什么支持各种文件图片以及mp4的播放,因为在这里都有受支持的格式。并且都是相对应的模块,如果想增加新的格式的文件类型,不是只在这边添加就行,需要让开发写对应的模块
types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

 .....
 #比如flv格式的流媒体,因为有这个模块--with-http_flv_module
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;

补充2: nginx内置的变量

log_format  main    '$remote_addr - $remote_user [$time_local] "$request" '   
                     '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
#配置文件的格式和日志的格式一一对应
10.0.0.1 - - [04/Sep/2019:21:27:22 +0800] "GET /favicon.ico HTTP/1.1" 404 555 "http://10.0.0.7/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"

$remote_addr(如果有CDN会显示CDN的IP)------10.0.0.1
$remote_user [$time_local]------[04/Sep/2019:21:27:22 +0800]
"$request"(请求)------"GET /favicon.ico HTTP/1.1"
$status(状态码)------404
$body_bytes_sent(发送的字节数)------555
"$http_referer"(从哪里跳转)------"http://10.0.0.7/"
"$http_user_agent"(客户端平台系统)------"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"
"$http_x_forwarded_for"-------真实用户的客户端IP地址

五:Nginx网站配置

写虚拟主机配置

1)添加conf文件
    server {
            listen 80;
            server_name localhost;    #一般填写域名,现在没有域名,填本主机
    
            location / {              #这边为什么写根,其实当我们访问10.0.0.7时,会自动在后面加个根“10.0.0.7/”这个根是匹配浏览器输入的,在浏览器输入个域名,域名就会到nginx配置文件中找,location匹配输入的内容,匹配这个根,根告诉你在code下面找代码,找一个名index.html的代码返回给浏览器,如果echo "game" > /code/index.html,那么输入10.0.0.7会出现game,后面的index index.html的意思是为什么域名输入时不用加index,就能访问页面。
                   root /code;         
                   index index.html;    
            }
    } 
2)创建code目录并授权
    [root@web02 conf.d]# mkdir /code
    #查看哪个用户启用nginx,需要改成www用户
    [root@web02 ~]# ps -ef|grep nginx
    root      12384      1  0 20:42 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
    nginx     12385  12384  0 20:42 ?        00:00:00 nginx: worker process
    root      12542  12258  0 22:37 pts/0    00:00:00 grep --color=auto nginx
    [root@web02 ~]# chown -R www.www /code/
    #修改nginx主配置文件中的user,改成www
    [root@web02 ~]# vim /etc/nginx/nginx.conf 
    #测试语法
    [root@web02 ~]# nginx -t
    nginx: [warn] conflicting server name "localhost" on 0.0.0.0:80, ignored    #这边报错,因为没有域名,有两个虚拟主机配置(default,game)同时监听两个80端口,所以会冲突 
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok            #后期可以通过域名和端口不同在区分,现在可以把default删除或者gz打包
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    #关闭default.conf后重启nginx
    nginx -s reload

注意1:如果两个端口冲突(default.conf/games.conf),会按照/etc/nginx/conf.d/目录下的文件顺序来读取文件

#默认安顺序来读取,先读取default.conf
[root@web02 code]# ll /etc/nginx/conf.d/
total 8
-rw-r--r-- 1 root root 1093 Aug 13 23:02 default.conf
-rw-r--r-- 1 root root  101 Sep  6 10:07 game.conf

注意2:如果一个页面有多个location,且站点目录都一样,可以如下方式:

For example:
server {
        listen 80;
        server_name localhost;

        location / {
                root /code;
                index index.html;
        }
}
        location / {
                root /code;
                index index.html;
        }
}

#可以直接写成如下方式:
server {
        listen 80;
        server_name localhost;
        root /code;
        index index.html;
        
        location / {
                
        }
}
        location / {
              
        }
}
#这是因为对于location,server就是全局,对于server,nginx.conf的http层就是全局

备注:一定要理解配置文件中的location,如果code目录里不是index.html,而是/jw/index.html,那么配置文件要改成root /code/jw

六:Nginx配置虚拟机三种方式

1.基于主机多IP方式

1).配置多网卡多IP的方式

server {
    ...
    listen 10.0.0.10:80;
    ...
}
 
server {
    ...
    listen 10.0.0.11:80;
    ...
}

2).配置单网卡多IP的方式

#添加一个IP
[root@web01 ~]# ip addr add 10.0.0.11/24 dev eth0
 
# 虚拟机配置方案
[root@web01 ~]# cat /etc/nginx/conf.d/addr1.conf
server {
    ...
    listen 10.0.0.10:80;
    ...
}
 
[root@web01 ~]# cat /etc/nginx/conf.d/addr2.conf
server {
    ...
    listen 10.0.0.11:80;
    ...
}

2.基于端口的配置方式

#Nginx多端口虚拟主机方式,具体配置如下

#仅修改listen监听端口即可, 但不能和系统端口出现冲突
 
[root@web01 ~]# cat /etc/nginx/conf.d/port1.conf
server {
    ...
    listen 80;
    ...
}
 
[root@web01 ~]# cat /etc/nginx/conf.d/port2.conf
server {
    ...
    listen 81;
    ...
}
 
[root@web01 ~]# cat /etc/nginx/conf.d/port3.conf
server {
    ...
    listen 82;
    ...
}

3.基于多域名方式(常用)

注意点:如果测试记得自己电脑hosts文件添加主机地址和域名/windows/system2/drive/etc/hosts

1.创建对应的web站点目录以及程序代码
[root@web01 ~]# mkdir /soft/code/{server1,server2}
[root@web01 ~]# echo "server1" > /code/server1/index.html
[root@web01 ~]# echo "server2" > /code/server2/index.html

2.配置不同域名的虚拟主机
[root@web02 ~]# cat /etc/nginx/conf.d/server1.conf
server {
    listen       80;
    server_name  1.oldboyedu.com;
    root /code/server1;
    index index.html;
    ...
}
[root@web01 ~]# cat /etc/nginx/conf.d/server2.conf
server {
    ...
    listen       80;
    server_name  2.oldboyedu.com;
    root /code/server2;
    index index.html;
}

七:Nginx日志管理

Nginx有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志。日志格式通过log_format命令定义格式。

1.日志包含的内置变量

$remote_addr        # 记录客户端IP地址(非真实客户端,如果架构中有CDN,客户访问先到CDN,那么CDN就是nginx的客户端,这边显示的就是CDN的地址,所以不是真实的客户端)
$remote_user        # 记录客户端用户名
$time_local         # 记录通用的本地时间
$time_iso8601       # 记录ISO8601标准格式下的本地时间
$request            # 记录请求的方法以及请求的http协议
$status             # 记录请求状态码(用于定位错误信息)
$body_bytes_sent    # 发送给客户端的资源字节数,不包括响应头的大小
$bytes_sent         # 发送给客户端的总字节数
$msec               # 日志写入时间。单位为秒,精度是毫秒。
$http_referer       # 记录从哪个页面链接访问过来的
$http_user_agent    # 记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端IP地址
$request_length     # 请求的长度(包括请求行, 请求头和请求正文)。
$request_time       # 请求花费的时间,单位为秒,精度毫秒
# 注:如果Nginx位于负载均衡器,nginx反向代理之后, web服务器无法直接获取到客户端真实的IP地址。
# $remote_addr获取的是反向代理的IP地址。 反向代理服务器在转发请求的http头信息中,
# 增加X-Forwarded-For信息,用来记录客户端IP地址和客户端请求的服务器地址。

2.针对域名配置日志

备注:可以针对location不记录日志:access_log off ,也可以但单独对location记录日志,一般很少这么操作

server {
    listen 80;
    server_name code.oldboy.com;

    #将当前的server网站的访问日志记录至对应的目录,使用abc格式,abc是在server的全局nginx.conf的http层定义的变量,一般一个虚拟主机(server)定义一个变量
    access_log /var/log/nginx/code.oldboy.com.log abc;
    location / {
        root /code;
        index index.html;
    }

    #当有人请求改favicon.ico时,不记录日志
    location /favicon.ico {
        access_log off;
        return 200;
    }
}

3.日志切割

备注:nginx自带日志切割功能

[root@nginx conf.d]# cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        daily                   # 每天切割日志
        missingok               # 日志丢失忽略
        rotate 52               # 日志保留52天
        compress                # 日志文件压缩
        delaycompress           # 延迟压缩日志
        notifempty              # 不切割空文件
        create 640 nginx adm    # 创建出来新日志文件权限 640,属主(nginx)和属组(adm)
        sharedscripts
        postrotate      # 切割日志执行的命令 
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}

一:Nginx初级介绍

标签:并且   配置   web服务   请求头   icon   logs   key   address   重启nginx   

原文地址:https://www.cnblogs.com/captain-jiang/p/12078407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!