nginx配置文件及虚拟主机

发布时间 2023-04-09 16:43:01作者: 大意了没有闪

最小配置

nginx.conf去掉注释字段后剩余的字段

# 工作进程数量,配置为对应cpu核数量效果最好
worker_processes  1;

events {
    # 每个worker进程能创建的链接数量,默认即可
    worker_connections  1024;
}

http {
    # 引入响应头的Content-Type值
    include       mime.types;
    # 默认的Content-Type值,如果返回文件的类型在mime.types中未定义,则使用这个默认类型
    default_type  application/octet-stream;
    # 数据零拷贝
    # off:简单来讲就是用户请求一个文件时,nginx读取文件内容到自己的应用内存,再从自己的应用内存发送到计算机的网络接口,网络接口收到数据后再推送给用户
    # on:nginx不加载文件内容到自己的应用程序,给网络接口发送一个信号,网络接口直接读取文件然后发送给用户
    sendfile        on;
    # 请求连接超时时间
    keepalive_timeout  65;

    # 虚拟主机
    server {
        # 监听的主机端口号
        listen       80;
        # 当前主机的主机名或者域名(域名配置后在解析时会变成当前主机的ip地址),多个空格隔开
        server_name  localhost;
        # 域名后面跟的子目录或路径(uri)
        # url:完整的链接,如:http://tt.com/book/1
        # uri:用来匹配资源,域名之后的部分,如:/book/1
        # location:指向uri
        location / {
            # 网站的根目录
            root   html;
            # 默认页
            index  index.html index.htm;
        }
        # 发生服务端错误(500 502 503 504)时转向http://tt.com/50x.html页面
        error_page   500 502 503 504  /50x.html;
        # 指定http://tt.com/50x.html的路径
        location = /50x.html {
            # 在html这个目录里去找50x.html
            root   html;
        }
    }
}

虚拟主机

# 在hosts设置2个域名
# 修改hosts文件方法(1:给hosts文件的Users组分配修改权限,修改保存后再去掉Users组的修改权限。2:把hosts文件拷贝到其它地方,修改完在覆盖回去)
192.168.232.128    book.tt.com
192.168.232.128    game.tt.com

创建两个网站

[root@localhost www]# tree /home/www/game/ /home/www/book/
/home/www/game/
└── index.html
/home/www/book/
└── index.html

配置

需要保证:listem + server_name 唯一

book.tt.com -> /home/www/book/
game.tt.com -> /home/www/game/

server {
    listen       80;
    server_name  game.tt.com;
    location / {
        root   /home/www/game;
        index  index.html index.htm;
    }
}

server {
    listen       80;
    server_name  book.tt.com;
    location / {
        root   /home/www/book;
        index  index.html index.htm;
    }
}

server_name

匹配有先后顺序,匹配到某个节点后就不会再往后去找了,所以范围小的应该放前面

精确匹配

server_name  game.tt.com dota2.tt.com;

通配符匹配

除了book.tt.com以外,其它都匹配到这里*.tt.com

server {
    ...
    server_name  book.tt.com;
    ...
}
server {
    ...
    server_name  *.tt.com;
    ...
}

通配符匹配结尾

192.168.232.128 book.tt.net
192.168.232.128 book.tt.org

server {
    listen       80;
    server_name  book.tt.com;
    location / {
        root   /home/www/book;
        index  index.html index.htm;
    }
}

server {
    listen       80;
    server_name  book.tt.*;
    location / {
        root   /home/www/game;
        index  index.html index.htm;
    }
}
# 结果:访问book.tt.net,book.tt.org都显示game的页面

正则匹配

# 以数字开头 tt.com结尾
server_name  ~^[0-9]+\.tt\.com$;