CasperG's Blog

Some People choose to see the ugliness in the world, the disarray. I choose to see the beauty.

Nginx配置新版2022

Nginx配置新版2022


一、Conf.d文件夹的应用

在新版nginx中,假设网站不需要每次都编辑/etc/nginx/nginx.conf。现可将xxx.conf放入/etc/nginx/conf.d/文件夹中,nginx会自动识别配置。

  • /etc/nginx/conf.d/xxx.conf的编写格式
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    server { # http访问配置
    listen 80;
    listen [::]:80;
    server_name ohuai.guru;
    rewrite ^(.*)$ https://ohuai.guru$1 permanent; # 将http重定向至https
    }

    server { # https访问配置
    listen 443; # ipv4
    listen [::]:443; # ipv6
    server_name ohuai.guru;
    ssl on;
    ssl_certificate /blog/ssl/ohuai.guru_bundle.crt;
    ssl_certificate_key /blog/ssl/ohuai.guru.key;
    ssl_session_timeout 5s;
    ssl_prefer_server_ciphers on;

    location / {
    root /blog/gurh-blog/public;
    index index.html;
    }
    }
    /etc/nginx/conf.d/xxx.conf中,只需要填写server{}部分http{}部分不用填写。

二、 nginx反代

通过nginx反代,原本需要用主域名+端口号访问的服务可以通过二级域名来访问,并且此访问使用https.

  1. 在cloudflare添加A记录将服务器ip解析至二级域名
  2. 申请二级域名证书
  3. /etc/nginx/conf.d/中添加xx.conf文件,
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    server {
    listen 443;
    listen [::]:443;
    server_name code.ohuai.guru; # 二级域名
    ssl on;
    ssl_certificate /blog/ssl/code.ohuai.guru_bundle.crt; # 证书文件绝对路径
    ssl_certificate_key /blog/ssl/code.ohuai.guru.key;
    # 私钥文件绝对路径
    ssl_session_timeout 5s;
    ssl_prefer_server_ciphers on;

    location / {
    proxy_pass http://172.17.0.3:8443/; # 该服务容器的内网ip
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
    }
    }
    注意:proxy_pass中的网址必须以/结尾。