1.开始
主要更改端口、ip、代理地址、dist 包路径指向。注意语法和空格分号!!!每次修改 nginx.conf 后,建议按顺序执行:
nginx -t
nginx -s reload
2.nginx配置
nginx
server {
# 访问端口
listen 9000;
# 服务端接口 ip
server_name 192.168.100.100;
underscores_in_headers on;
# 状态监测与评价-前端
location /web {
# 打包后的 dist 文件包存放路径
alias /var/www/html/dist;
try_files $uri $uri/ /web/index.html;
index index.html index.htm;
# 添加缓存控制
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
location ^~/dev-api/ {
# 服务端接口地址
proxy_pass http://192.168.100.100:8080/;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Nginx-Proxy true;
# 添加超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
bash
# 目录结构应该是:
html/
├── dist/
│ ├── index.html
│ ├── js/
│ ├── css/
│ └── assets/
- 监听端口 :
9000 - 服务器地址 :
192.168.1.200 - 前端路径 :
/web(通过 alias 指向html/dist) - API 代理 :
/dev-api/→http://192.168.100.200:8080/ - 浏览器访问 :
http://192.168.100.200:9000/web
3.nginx 常见命令(当前 nginx 路径下执行)
bash
# 更改配置后需要重新加载配置
nginx -s reload
# 或
systemctl reload nginx
# Nginx 是否正常运行:
netstat -tlnp | grep 9000
# 检查语法是否正常
./nginx -t
# nginx.conf syntax is ok
# nginx.conf test is successful
# 输出正常
# 或者完全重启
nginx -s stop
# nginx启动
start nginx
# 或
# 双击 nignx.exe 会出现黑色窗口一闪而过(正常现象),但不方便停止和重载配置
# 或 linux 系统启动
sudo systemctl start nginx
# 查看运行状态
sudo systemctl status nginx
快速测试
bash
# 在 dist 文件夹下创建一个 test.html 文件
echo "<h1>Test Page</h1>" > /usr/local/nginx/html/dist/test.html
# 访问浏览器:http://192.168.1000.200:9000/web/test.html 是否能访问到