跳到主要内容

nginx应用配置

  • web项目部署在nginx,不同的应用,nginx配置是不太一样的,比如spa应用、ssr应用
  • nginx部署ssr应用,还需要配置node服务的反向代理,因为ssr应用需要启动node服务
    • 注意node服务的端口
  • nginx配置的upstream实现负载均衡,比如node服务,可以配置多台 nodejs 节点,做负载均衡

web spa应用配置​

  • 传统的web的spa单页面应用
bash
server {
listen 80;
server_name spa.example.com;
root /var/www/spa/dist; # 编译后的静态资源路径
index index.html;

location / {
try_files $uri $uri/ /index.html; # 处理前端路由(如Vue Router)
}

location /api/ {
proxy_pass http://backend:3000; # 后端服务地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1; # 支持HTTP/1.1长连接
}
}

nuxt应用配置​

常用的配置​

bash
server {
listen 80;
server_name nuxt.example.com;

location / {
proxy_pass http://127.0.0.1:3000; # Nuxt服务端口
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; # 支持WebSocket
proxy_set_header Connection "upgrade";
}

}

负载均衡配置:​

  • upstream根据需要来配置,不加也行
bash
# 通过 upstream nodejs 可以配置多台 nodejs 节点,做负载均衡
# keepalive 设置存活时间。如果不设置可能会产生大量的 timewait
# proxy_pass 反向代理转发 http://nodejs

upstream nodenuxt {
server 127.0.0.1:3000; # nuxt 项目监听端口
keepalive 64;
}
server {
listen 80;
server_name example.com www.example.com;

location / {
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-Nginx-Proxy true;
proxy_cache_bypass $http_upgrade;
# 转发反向代理nuxt的node服务 (这里需要对应upstream的名称)
# proxy_pass http://127.0.0.1:3000;
proxy_pass http://nodenuxt
}
}

next应用配置​

bash
server {
listen 80;
server_name next.example.com;

location / {
proxy_pass http://localhost:3009; # Next服务端口
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_cache_bypass $http_upgrade;

# 处理Next静态资源
location /_next/static {
alias /var/www/next/.next/static;
expires 365d;
access_log off;
}
}
}

应用的静态资源文件服务​

  • 处理所有以.html或.htm结尾的请求,从指定目录提供静态文件服务
  • 如当访问www.example.com/demo.html就会提供静态文件服务
bash
# 静态资源处理
location \~* \.(html|htm)$ {
root /data/www/static;
}