nginx反向代理vue项目


前言

项目描述:前端vue项目、后端Java项目、首页WordPress项目
客户要求:使用宝塔进行部署
需求描述:客户只有一个SSL单域名DV证书要求首页部署wordpress项目作为官网,/system为vue项目,/api为java后端项目

一、创建站点

1.添加站点

域名填写客户域名、根目录指向wordpress项目地址(此处带过不是重点)
在这里插入图片描述

2.添加ssl证书

将证书key、pem(crt)内容拷贝到内容中保存即可
在这里插入图片描述

二、反向代理vue项目

此处遇到的问题:
1.代理后静态文件(.css,.js)访问不到404
2.vue项目访问后端接口访问不到

1.添加反向代理

代理名称随便取
代理目录意思为解析域名后/xxx的转发到目标URL
在这里插入图片描述
默认创建如下


location ^~ /system
{
    
    
    proxy_pass http://xzzzz:9002/;
    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 REMOTE-HOST $remote_addr;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_http_version 1.1;
    # proxy_hide_header Upgrade;

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache
    
    
    set $static_filebdpe8eQS 0;
    if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" )
    {
    
    
    	set $static_filebdpe8eQS 1;
    	expires 1m;
        }
    if ( $static_filebdpe8eQS = 0 )
    {
    
    
    add_header Cache-Control no-cache;
    }
}

添加下面配置解决静态文件404问题
注意路径后边一定要加/

location ^~ /system.*\.(js|css)?$
{
    
    
    proxy_pass http://xxxxxx:9002/;
    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 REMOTE-HOST $remote_addr;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_http_version 1.1;
    # proxy_hide_header Upgrade;

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache
    
    
    set $static_filebdpe8eQS 0;
    if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" )
    {
    
    
    	set $static_filebdpe8eQS 1;
    	expires 1m;
        }
    if ( $static_filebdpe8eQS = 0 )
    {
    
    
    add_header Cache-Control no-cache;
    }
}

2.更改vue项目配置

1.更改router,添加/system路径前缀

export default new Router({
    
    
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({
    
     y: 0 }),
  routes: constantRoutes,
  base:'/system'
})

2.更改打包后静态文件的访问地址添加/system路径前缀
vue.config.js
在这里插入图片描述如果是vite构建的则修改base字段

3.修改反向代理配置

解决vue跨域问题

	location /prod-api/ {
    
    
		proxy_set_header Host $http_host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header REMOTE-HOST $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass http://www.xxx.com/api;
	}

猜你喜欢

转载自blog.csdn.net/qq_43548590/article/details/133171797