Nginx 配置文件说明

  • Nginx 配置文件介绍
  • server配置语法
  • server虚拟主机配置
  • 基于域名虚拟机配置
  • 基于端口配置虚拟机
  • 基于IP配置虚拟机
  • location 配置语法
  • location匹配规则(URL匹配)
  • 精确匹配:`=`
  • 大小写敏感 区分大小写:`~`
  • 大小写忽略:`~*`
  • 只匹配以 uri 开头: `^~ `
  • 其他匹配都不成功 就匹配此项:`/`
  • location匹配跳转(URL匹配)
  • @ 语法,内部跳转
  • URL 重写
  • return:该指令用于结束规则的执行并返回状态码给客户端
  • rewrite:匹配到请求URI,重写到新的URI
  • 资源重定向实现
  • 域名重定向实现
  • 防盗链原理和实现
  • 安全设置
  • 反向代理
  • 反向代理配置:LNMPA
  • 隐藏版本号
  • HTTPS 和 CA

Nginx 配置文件介绍

查看nignx目录下的配置文件:/usr/local/nginx/nginx.conf

  • http => server => location :递进关系
#user  nobody;		=>	nginx子进程启动用户,如果编译的时候没有指定可以在这里指定
worker_processes  1;		=>	子进程数量  一般调整为cpu核数或者倍数



#l 错误日志定义
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;



#pid        logs/nginx.pid;			=>	进程pid 存储文件



#l	事件
events {
    #l 每个子进程的连接数         nginx当前并发量  worker_processes * worker_connections
    worker_connections  1024;
}



#http协议段
http {

    #l	引入  文件扩展名和与文件类型映射表
    include       mime.types;			

    #l	默认文件类型,默认以二进制流的方式传输
    default_type  application/octet-stream;

    #l	访问日志access.log的格式
    #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;

    #	linux内核  提供文件读写的机制,加快读写
    sendfile        on;			=>	sedfile开启,tcp_nopush默认也跟着开启
    #l 优化网络连接的机制
    #tcp_nopush     on;

    #keepalive_timeout  0;		=>	0不设置连接超时时间,不会主动断开与客户端连接,除非客户端主动发送断开请求

    #长连接超时时间  单位为s
    keepalive_timeout  65;

    #gzip压缩
    #gzip  on;


    #server虚拟主机的配置
    server {

        #l	监听端口
        listen       80;

        #域名  可以有多个 用空格分隔
        server_name  localhost;			=>	代表服务绑定的域名

        #l	默认编码
        #charset koi8-r;

        #access_log  logs/host.access.log  main;


        #	location 用来匹配url
        location / {

            #l	默认访问的网站路径
            root   html;

            #l	默认访问页面 从前往后的顺序查找
            index  index.html index.htm;
        }


#l	错误日志,当出现访问错误时后找到相关错误文件返回客户端,默认是开启
        #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		=>	php请求传送到Apache的80端口
        #
        #location ~ \.php$ {			=>	反向代理
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000	=>	以FastCGI 请求的php文件发送到php-fpm去解析
        #
        #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		=>	.htaccess 分布式重写配置文件,
        																	如果Apache和Nginx目录是同一个,禁止访问这个文件,
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

	#l	虚拟主机配置
    # 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 配置
    # 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配置语法

server虚拟主机配置

  • 在实际生产业务环境中,一台web服务器,需要使用多个网站部署。搭建vhost虚拟机主机实现不同域名,解析绑定到不同的目录。
  • 在http中新建一个server

一般server虚拟主机配置有三类:

①基于域名,将域名配置到server_name上

②基于IP,将IP配置到server_name上

③基于端口,将端口配置到listen

基于域名虚拟机配置

第一步:修改配置文件,增加新的server配置
# vim /usr/local/nginx/conf/nginx.conf

server{
    #监听端口
    listen 80
    #配置虚拟机
    server_name shop.lnmp.com			=>	指定域名
    root html/tp5shop;					=>	指定这个域名所在项目目录
    location / {						=>	指定默认访问文件,这个可以提到各个server上面,这样就不用每个都写	
        index index.php index.html index.htm
    }
    location ~ \.php$ {						=>	解析php请求
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }


第二步:重载一下Nginx配置文件
# systemctl reload nginx

# 第三步:在html目录下创建shop.lnmp.com 这个项目的目录
# cd /usr/local/nginx/html
# mkdir shop			=>	将项目文件放到此处即可


访问:
# shop.lnmp.com/index.php

基于端口配置虚拟机

  • 修改listen 端口
第一步:修改配置文件,增加新的server配置
# vim /usr/local/nginx/conf/nginx.conf

server{
    #监听端口
    listen 8181;		=>	端口修改为8181
    #配置虚拟机
    server_name shop.lnmp.com			=>	指定域名
    root html/tp5shop;					=>	指定这个域名所在项目目录
    location / {						=>	指定默认访问文件,这个可以提到各个server上面,这样就不用每个都写	
        index index.php index.html index.htm
    }
    location ~ \.php$ {						=>	解析php请求
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }


第二步:重载一下Nginx配置文件
# systemctl reload nginx

# 第三步:在html目录下创建shop.lnmp.com 这个项目的目录
# cd /usr/local/nginx/html
# mkdir shop			=>	将项目文件放到此处即可

访问:
# shop.lnmp.com:8081/index.php

基于IP配置虚拟机

  • 临时绑定一个IP:ifconfig ens33:1 10.1.1.22
第一步:修改配置文件,增加新的server配置
# vim /usr/local/nginx/conf/nginx.conf

server{
    #监听端口
    listen 80;		
    #配置虚拟机
    server_name 10.1.1.22			=>	指定IP
    root html/blogs;					=>	指定这个IP所在项目目录
    location / {						=>	指定默认访问文件,这个可以提到各个server上面,这样就不用每个都写	
        index index.php index.html index.htm
    }
    location ~ \.php$ {						=>	解析php请求
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }


第二步:重载一下Nginx配置文件
# systemctl reload nginx

# 第三步:在html目录下创建shop.lnmp.com 这个项目的目录
# cd /usr/local/nginx/html
# mkdir blogs			=>	将项目文件放到此处即可

访问:
# 10.1.1.22/index.php

location 配置语法

location 只能写到server段、或者location嵌套location

官方文档:http://nginx.org/en/docs/http/ngx_http_core_module.html#location

location匹配规则(URL匹配)

nginx formdata配置 nginx配置文件说明_php

精确匹配:=

基本语法:

location = / {
    #规则
}
#l 则匹配到 http://www.example.com/ 这种请求

演示:

  • 代表只要匹配到server_name 这个域名或IP,就会显示出location = /的内容,
server {
        listen       80;
        server_name  10.1.1.100;
        root html/tp5shop/public;
        #root html;
        charset utf8;
        autoindex on;
       access_log                  logs/10.1.1.100_access.log       mylogs;
        #access_log  logs/host.access.log  main;
        fancyindex on;
        fancyindex_exact_size off;
        location = / {						=>	这这这。。。。。。。。。。。。。。。。。。。。。。。。
            default_type text/html;
               echo "<h1>=,严格等于<h1 />";
        #}



        location / {
         #   root   html;
            index  index.php index.html index.htm;
        }
        location ~ \.(js|ico|gif|jpg|jpeg|png|html|htm)$ {
              expires 1h;
        }
        #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  $document_root$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 formdata配置 nginx配置文件说明_html_02

大小写敏感 区分大小写:~

基本语法:

location ~ /Example/ {
    #规则
}

#l 请求示例:
#	http://www.example.com/Example/  [成功]
#	http://www.example.com/example/  [失败]


大小写忽略:~*

基本语法:

location ~* /Example/ {
    #规则
}

#l 请求示例:
#	http://www.example.com/Example/  [成功]
#	http://www.example.com/example/  [成功]


只匹配以 uri 开头: ^~

基本语法:

location ^~ /img/ {
    #规则
}

请求实例:以 /img/ 开头的请求,都会匹配上
#	http://www.example.com/img/a.jpg   [成功]
#	http://www.example.com/img/b.mp4 [成功]

#	http://www.example.com/bimg/b.mp4 [失败]
#	http://www.example.com/Img/b.mp4 [失败]


其他匹配都不成功 就匹配此项:/

  • 如果路径是资源文件是存在的,会优先获取资源文件
  • location匹配优先级:(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)

基本语法:

location / {
   #规则
}

location匹配跳转(URL匹配)

@ 语法,内部跳转

@ 语法用于Nginx内部跳转:

  • 可以指定返回的状态码是啥
  • 也可以指定到一个页面中
location /img/ {
    #如果状态码是404  就指定404的页面为什么,即跳转到@img_err
    error_page 404 = @img_err;
}    

location @img_err {    
    # 规则
    return  503;
}


nginx formdata配置 nginx配置文件说明_nginx formdata配置_03

nginx formdata配置 nginx配置文件说明_nginx_04

URL 重写

ngx_http_rewrite_module模块用于使用PCRE正则表达式更改请求URI,返回重定向,以及有条件地选择配置

官方文档地址:http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

return:该指令用于结束规则的执行并返回状态码给客户端

请求状态码文档:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status

基本语法:

#可以匹配到server location if中,推荐配置到location中
return 403;

nginx formdata配置 nginx配置文件说明_nginx formdata配置_05

rewrite:匹配到请求URI,重写到新的URI

  • rewrite语法 匹配到,替换为其他内容
  • 语法: rewrite 匹配内容 替代内容 标记

官方文档地址:http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

flag标记说明:

  • last :本条规则匹配完成后,继续向下匹配新的location URI规则,客户端URL地址不会发生跳转
  • break :本条规则匹配完成即终止,不再匹配后面的任何规则,客户端URL地址不会发生跳转
  • redirect :返回302临时重定向,浏览器地址会显示跳转后的URL地址
  • permanent :返回301永久重定向,浏览器地址栏会显示跳转后的URL地址

匹配顺序: 多条rewrite,从上到下匹配,匹配到之后就不在匹配其他rewrite规则。

资源重定向实现

业务需求描述:

  • 实际业务不存在index.html,需要重写访问index.php
  • URL为index.html,而实际访问的是index.php,对外被认为是html静态页面
  • 以上方案就是seo优化伪静态的使用,把真实的后端的页面,伪装为静态html页面。

基本语法:

location /{
	rewrite /index.html /index.php last;		=>	添加配置
}

nginx formdata配置 nginx配置文件说明_html_06

域名重定向实现

需求:

  • 网站的域名升级了,需要启用新的域名使用。
  • 但是用户却不知道,还可能使用旧的域名访问网站。
  • 需要把通过旧域名访问的来源,重定向到新的域名。
  • 把shop.lnmp.com的请求全部重定向到新域名www.shop.com

基本语法:

  • 写在server 段中,在旧的server中写上

nginx formdata配置 nginx配置文件说明_html_07

rewrite / http://www.shop.com permanent;		=>	使用永久重定向www.shop.com
  • 比如将10.1.1.100 永久重定向到 10.1.1.111中。
  • 临时绑定一个IP:ifconfig ens33:1 10.1.1.111


防盗链原理和实现

nginx formdata配置 nginx配置文件说明_html_08

官方文档:https://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers

业务需求描述:

  • 域名A的资源文件,经常被域名B直接调用访问。
  • 而用户经常访问域名B,看到的资源(图片等)以为是域名B的,实际则是域名A的。
  • 但是域名A没有从中获得任何收益,缺要给域名B来源的访问耗费服务器资源和带宽。

  • 所以,禁止域名B直接访问和调用域名A的资源的方式,就被称为"防止盗链"
  • nginx formdata配置 nginx配置文件说明_nginx_09

基本语法:

定义允许访问的域名来源
valid_referers none blocked servername;			=>	none blocked  没有referer的情况,直接访问资源的情况
if ($invalid_referer) {}						=>	验证referer值,如果验证不通过就有$invalid_referer

演示:

第一步:设置两个虚拟主机

  • A域名为:a.com
  • B域名为:b.com

nginx formdata配置 nginx配置文件说明_html_10

第二步:在B域名中设置可以访问A域名的图片资源

# cd /usr/local/nginx/html

# echo '<img src="http://a.com/static/home/img/banner1.jpg" />' >> img.html

nginx formdata配置 nginx配置文件说明_html_11

第三步:在A域名中设置防盗链,不允许非本域名的referer 头请求访问图片等静态资源

#图片请求防盗链
location ~* \.(jpg|png|jpeg|gif|bmp) {				=>	定义哪些资源不允许别的域名使用
    valid_referers www.shop.com;					=>	只要refeer 头不是本站的就会产生$invalid_referer
	if ($invalid_referer) {							=>	一旦有变量就返回404
  	    return 404;
	}
	}


安全设置

反向代理

正向代理:

  • 特点:知道自己使用了代理,需要填写代理服务器的IP等相关连接信息

常见于代理客户端上网等操作

nginx formdata配置 nginx配置文件说明_nginx formdata配置_12


反向代理:

  • 特点:用户是无感知的,不知道使用了代理服务器。反向代理服务器是和真实访问的服务器是在一起的,有关联的。
  • 作用:可以根据实际业务需求,分发代理页面到不同的解释器,可以隐藏真实服务器的路径

常见于代理后端服务器

nginx formdata配置 nginx配置文件说明_nginx formdata配置_13

反向代理配置:LNMPA

基本语法:

  • Nginx中配置
# proxy the PHP scripts to Apache listening on 127.0.0.1:80		=>	代理php脚本到Apache的80端口

location ~ \.php$ {					=>	反向代理
    proxy_pass   http://127.0.0.1;
 }

官方文档:http://nginx.org/en/docs/http/ngx_http_proxy_module.html

nginx formdata配置 nginx配置文件说明_nginx formdata配置_14

第一步:安装一个Apache,并修改其配置文件

# yum install -y httpd

# vim /etc/httpd/conf/httpd.conf
	42 Listen 8080					=>	将Apache端口改一下,因为80端口现在被Nginx占了

# systemctl start httpd 				=>	启动Apache

第二步:配置nginx的server并进行转发

  • 需要新建一个server段,然后卸载location 中
  • 访问b.com就是访问Apache的8080端口
# vim /usr/local/nginx/conf/nginx.conf
     server {
        listen 80;
        server_name b.com;
        root html;
        location / {
           proxy_pass http://127.0.0.1:8080;
        }
}

访问b.com:其实就是访问Apache

nginx formdata配置 nginx配置文件说明_php_15

隐藏版本号

Nginx对外提供服务,为了避免被针对某个版本的漏洞进行攻击。经常做法是隐藏掉软件的版本信息。提供一定的安全性。

#将以下配置加入到http段配置中
server_tokens off;

没隐藏时:

nginx formdata配置 nginx配置文件说明_nginx_16

加入配置隐藏:

nginx formdata配置 nginx配置文件说明_nginx_17

HTTPS 和 CA

【Nginx】如何使用自签CA配置HTTPS加密反向代理访问?看了这篇我会了!!

配置:

server {
        listen       443 ssl;
        #绑定好域名
        server_name  a.com;
        #指定证书相关位置
        ssl_certificate      /usr/local/nginx/conf/a.com.crt;
        ssl_certificate_key  /usr/local/nginx/conf/a.com.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;
        }
    }

# http 重定向跳转到https
server {
    listen 80;
    server_name a.com;
    rewrite / https://a.com permanent;
}