Nginx代理以及面向未来的HTTP

时间:2022-07-23
本文章向大家介绍Nginx代理以及面向未来的HTTP,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

windows 下使用 nginx

通过官网下载 Nginx,将其解压。在命令行内输入./nginx.exe 即可启动。

基础代理配置

如果启动的 nginx 进程过多,可能会导致代理不生效! 通过 taskkill /IM nginx.exe /F 命令可以清除所有 nginx 进程。

  1. 通过 include server/*.conf 实现为单独一个站点设置配置文件

此配置代表将 server 文件下的所有 conf 文件导入。

http{
    include server/*.conf
}
  1. 最简单的代理 以上配置表示 当访问 test.com 时会映射到本地 8888 端口。$host 表示请求的地址。
server{
    listen 80;
    server_name test.com;
    location /{
        proxy_pass http://127.0.0.1:8888;
        # 修改代理头为请求的地址
        proxy_set_header Host $host;
    }
}

代理缓存

proxy_cache_path cache levels=1:2 keys_zone=my_cache:10m;
server{
    listen        80;
    server_name test.com;
    location / {
        proxy_pass http://127.0.0.1:8888;
        # 修改代理头为请求的地址
        proxy_set_header Host $host;
        # 设置缓存(名字与上方对应)
        proxy_cache my_cache;
    }
}

可以使用 Vary 对不同请求头设置缓存。

HTTPS

证书生成命令:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout localhost-privkey.pem -out localhost-cert.pem
  • 通过 nginx 部署 https 服务
server{
    listen        ssl;
    server_name test.com;

    ssl on;
    ssl_certificate_key ../certs/localhost-privkey.pem;
    ssl_certificate ../certs/localhost-cert.pem;

    location / {
        proxy_pass http://127.0.0.1:8888;
        # 修改代理头为请求的地址
        proxy_set_header Host $host;
    }
}

其中将证书放到了根目录下 certs 文件夹下。

  • 访问自动跳转 https
server{
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name test.com;
    return 302 https://$server_name$request_url;
}

HTTP2 的优势

  • 信道复用
  • 分帧传输
  • Server Push HTTP1.1 中

HTTP2 中

通过 nginx 设置 HTTP2

server{
    listen        ssl http2;
    http2_push_preload on;
}

http2 必须在 https 的基础上开启。