前端通过nginx部署一个本地服务的方法

前端通过nginx部署一个本地服务的方法:

1.下载ngnix

nginx

下载完成后解压缩后运行nginx.exe文件

2.打包你的前端项目文件

javascript 复制代码
yarn build 

把生成的dist文件复制出来,替换到nginx的html文件下

3.配置conf目录的nginx.conf文件

主要配置server监听

javascript 复制代码
    server {
        listen       8088;
        server_name  localhost;

        location / {
            root  D:\\nginx-1.26.2\\nginx-1.26.2\\html;
            try_files $uri $uri/ @router;
            index  index.html index.htm;
        }

        location /api/ {
                proxy_pass http://localhost:1001/;  #匹配到/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;
                proxy_set_header X-Forwarded-Proto $scheme;
        }

        # 处理前端路由的 named location
        location @router {
            # 这里通常指向你的前端入口文件,例如 index.html
            # 也可以在这里进行更复杂的反向代理设置
            rewrite ^/(.*)$ /index.html last;
        }
        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

root D:\nginx-1.26.2\nginx-1.26.2\html;配置静态文件的目录,

正常是单斜杠,如果报错就试试双斜杠

location /api/ 匹配到/api/关键字可以转换到指定后端服务下

try_files uri uri/ @router; location @router 是为了避免刷新报错

4.运行nginx服务

运行cmd 运行到nginx服务的目录下,运行服务

javascript 复制代码
cd xxxx/nginx-1.26.2
nginx -t 
nginx -s reload //重新运行

以上配置完成后打开localhost:8088就可以打开前端项目了。

相关推荐
爱学习的狮王几秒前
window10和ubuntu22.04双系统之卸载ubuntu系统
linux·运维·ubuntu
JosieBook6 分钟前
【web应用】基于Vue3和Spring Boot的课程管理前后端数据交互过程
前端·spring boot·交互
刘大猫.13 分钟前
npm ERR! cb() never called!
前端·npm·node.js·npm install·npmm err·never called
咔咔一顿操作17 分钟前
常见问题三
前端·javascript·vue.js·前端框架
上单带刀不带妹19 分钟前
Web Worker:解锁浏览器多线程,提升前端性能与体验
前端·js·web worke
电商API大数据接口开发Cris35 分钟前
Node.js + TypeScript 开发健壮的淘宝商品 API SDK
前端·数据挖掘·api
还要啥名字37 分钟前
基于elpis下 DSL有感
前端
一只毛驴42 分钟前
谈谈浏览器的DOM事件-从0级到2级
前端·面试
用户8168694747251 小时前
封装ajax
前端
pengzhuofan1 小时前
Web开发系列-第13章 Vue3 + ElementPlus
前端·elementui·vue·web