Nginx 前端部署配置

1、Nginx 默认配置

Nginx 的默认配置位于 nginx.conf 文件中。根据安装方式和操作系统不同,它的位置可能略有不同,一般在以下目录中:

  • Linux:/etc/nginx/nginx.conf
  • Windows:C:\nginx\conf\nginx.conf
  • MacOS:/usr/local/etc/nginx/nginx.conf

以下是 Nginx 默认配置的示例:

user  nginx;
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;
    #    }
    #}
}

上面的配置文件定义了 Nginx 的一些基本选项,如用户、工作进程数、日志文件位置等。它还定义了 NGINX 事件块,并为HTTP请求提供了一些基本配置,如文件类型映射、日志格式、发送文件等。

请注意,这是 Nginx 默认的配置,您可以根据您的需求对其进行修改。在生产环境中,建议您对配置文件进行定制以实现最佳性能。

为了使 Nginx 适合您的特定需求,您可以对配置文件进行更改。以下是一些常见的配置任务:

  1. 更改端口:默认端口为80,但您可以更改它来避免与其他服务的冲突。

  2. 指定服务器名称:通过指定服务器名称,您可以为您的服务器创建自定义 DNS 名称。

  3. 配置虚拟主机:通过配置虚拟主机,您可以同时在一台服务器上运行多个网站。

  4. 启用 SSL/TLS:通过启用 SSL/TLS,您可以加密您的网站数据并保护它们免受黑客攻击。

  5. 配置代理:通过配置代理,您可以将请求从一台服务器转发到另一台服务器。

这些是 Nginx 配置的一些基本任务,您可以通过搜索互联网获得有关如何进行这些任务的详细信息。

2、 Nginx 前端部署基本配置

前端代码编译打包时的后台接口父地址配置(需与 Nginx 代理转发配置节点的 location 配置一致):

# 后台接口父地址
VITE_GLOB_API_URL=/api

2.1、根目录发布

前端代码编译打包时的发布路径配置:

# 发布路径
VITE_PUBLIC_PATH = /

在 Nginx 中配置前后端分离时,前端部署基本配置的示例:

server {
    listen 80;
    server_name example.com;

    location / {
        root /path/to/your/dist;
        index index.html index.htm;

        # 用于配合 history 路由模式使用
        try_files $uri $uri/ /index.html;
    }

    location /api {
        proxy_pass http://service_api_ip:service_api_port/service_api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

上面的配置定义了一个服务器,监听 80 端口,服务器名为 example.com,访问地址为 http://example.com。前端文件的根目录是 /path/to/your/dist。当用户请求根目录时,Nginx 将尝试使用 try_files 命令提供请求的文件。如果文件不存在,则返回 /index.html。

当用户请求/api 时,请求将被代理到后端服务器的相应端口,并设置了一些代理头,如 Host、X-Real-IP、X-Forwarded-For 等。这样,后端服务器就能获取到正确的客户端信息。

2.2、非根目录发布

前端代码编译打包时的发布路径配置:

# 发布路径
VITE_PUBLIC_PATH = /sub

 通过上述前端打包配置,打包后的静态资源 index.html 中引入的 JavaScript 文件和样式表文件等资源路径会被加上 /sub路径,代码示例:

<script src="/sub/_app.config.js?v=3.4.4-1678678452987"></script>
<title>Document</title>
<link rel="icon" href="/sub/logo.png" />
<script type="module" crossorigin src="/sub/assets/index.5a4fbf7c.js"></script>
<link rel="stylesheet" href="/sub/assets/index.f5d35357.css">
<link disabled="disabled" id="__VITE_PLUGIN_THEME-ANTD_DARK_THEME_LINK__" rel="alternate stylesheet"
      href="/sub/assets/app-antd-dark-theme-style.e3b0c442.css">

非根目录发布时,Nginx 前端部署基本配置的示例:

server {
    listen 80;
    server_name example.com;

    location /sub {
        root /path/to/your/dist;
        index index.html index.htm;

        # 用于配合 history 路由模式使用
        try_files $uri $uri/ /sub/index.html;
    }

    location /api {
        proxy_pass http://service_api_ip:service_api_port/service_api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

上述配置中,前端文件的所在目录是 /path/to/your/dist/sub。访问地址为http://example.com/sub

3、Nginx 配置 URL 地址后自动加上时间戳查询字符串(query string)

方法一:

可以使用 Nginx 的rewrite指令在首页 URL 地址后自动加上时间戳查询字符串。

下面是示例配置:

首页地址为:/index.html

server {
    # ...
    location / {
        # ...
        if ($request_uri ~ /index.html) {
            set $timestamp "$(date +%s)";
            rewrite ^ /index.html?timestamp=$timestamp;
        }
    }
    # ...
}

首页地址为:/

server {
    # ...
    location / {
        # ...
        set $timestamp "$(date +%s)";
        if ($request_uri ~ ^/$) {
            rewrite ^ /?timestamp=$timestamp;
        }
    }
    # ...
}

在此示例中,我们使用了rewrite指令将所有请求首页URL地址更改为带有时间戳查询字符串的URL地址。

可通过该方法解决手机端 H5 Nginx 更新部署后,导致得缓存问题,如显示空白页面或旧版本页面。

方法二:

可以使用 Nginx 的rewrite指令在 URL 地址后自动加上时间戳查询字符串。

下面是示例配置:

server {
    # ...
    location / {
        # ...
        set $timestamp "$(date +%s)";
        rewrite ^ /$request_uri?timestamp=$timestamp;
    }
    # ...
}

 在此示例中,我们使用了rewrite指令将所有请求 URL 地址更改为带有时间戳查询字符串的URL地址。

方法三:

在 nginx 配置中使用 $arg_timestamp 变量实现 url 自动加上时间戳查询字符串(query string)。以下是示例配置:

location / {
    if ($args = "") {
        rewrite ^ /?timestamp=$time_iso8601 permanent;
    }
    proxy_pass http://your_upstream;
}

上面的配置使用了 $args 变量检查当前请求是否存在查询字符串。如果不存在,则使用 rewrite 命令将请求重写为带有 timestamp 查询字符串的请求。$time_iso8601 变量表示当前时间,并以 ISO 8601 格式表示。

4、压缩配置

4.1、gzip 压缩

前端打包配置:

# 是否启用 gzip 或 brotli 压缩
# 选项值: gzip | brotli | none
# 如果需要多个可以使用“,”分隔
VITE_BUILD_COMPRESS = 'gzip'

# 使用压缩时是否删除原始文件,默认为 false
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE = false

开启 gzip 后,在前端打包时会同时生成 .gz 文件。

 

Nginx 开启 gzip,并配合 nginx 的 gzip_static 功能可以大大加快页面访问速度。

http {
  # 开启 gzip
  gzip on;
  # 开启 gzip_static
  # gzip_static 开启后可能会报错,需要安装相应的模块, 具体安装方式可以自行查询
  # 只有这个开启,前端打包的 .gz 文件才会有效果,否则不需要开启 gzip 进行打包
  gzip_static on;
  gzip_proxied any;
  gzip_min_length 1k;
  gzip_buffers 4 16k;
  # 如果 nginx 中使用了多层代理,必须设置这个才可以开启 gzip
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  gzip_vary off;
  gzip_disable "MSIE [1-6]\.";
}

4.2、brotli 压缩

前端打包配置:

# 是否启用 gzip 或 brotli 压缩
# 选项值: gzip | brotli | none
# 如果需要多个可以使用“,”分隔
VITE_BUILD_COMPRESS = 'brotli'

# 使用压缩时是否删除原始文件,默认为 false
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE = false

开启 brotli 后,在前端打包时会同时生成 .br 文件。

 

Nginx 开启 brotli,brotli 是比 gzip 压缩率更高的算法,可以与 gzip 共存不会冲突,需要 nginx 安装指定模块并开启即可。

http {
  # 开启 brotli 压缩
  # 需要安装对应的 nginx 模块,具体安装方式可以自行查询
  # 可以与 gzip 共存不会冲突
  brotli on;
  brotli_comp_level 6;
  brotli_buffers 16 8k;
  brotli_min_length 20;
  brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
}

 4.3、同时开启 gzip 与 brotli 压缩

前端打包配置:

# 是否启用 gzip 或 brotli 压缩
# 选项值: gzip | brotli | none
# 如果需要多个可以使用“,”分隔
VITE_BUILD_COMPRESS = 'brotli,gzip'

# 使用压缩时是否删除原始文件,默认为 false
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE = false

开启 gzip 和 brotli 后,在前端打包时会同时生成 .gz 和 .br 文件。

 

Nginx 同时开启 gzip 和 brotli 配置:

http {
  # 开启 gzip
  gzip on;
  # 开启 gzip_static
  # gzip_static 开启后可能会报错,需要安装相应的模块, 具体安装方式可以自行查询
  # 只有这个开启,前端打包的 .gz 文件才会有效果,否则不需要开启 gzip 进行打包
  gzip_static on;
  gzip_proxied any;
  gzip_min_length 1k;
  gzip_buffers 4 16k;
  # 如果 nginx 中使用了多层代理,必须设置这个才可以开启 gzip
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  gzip_vary off;
  gzip_disable "MSIE [1-6]\.";
    
  # 开启 brotli 压缩
  # 需要安装对应的 nginx 模块,具体安装方式可以自行查询
  # 可以与 gzip 共存不会冲突
  brotli on;
  brotli_comp_level 6;
  brotli_buffers 16 8k;
  brotli_min_length 20;
  brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
}

 

posted @ 2023-01-30 09:56  飞仔FeiZai  阅读(4809)  评论(0)    收藏  举报