Nginx下同域部署多个Vue项目(history路由模式),报404、500错误

一、环境

系统: windows
nginx: 1.20.2
nodejs: v10.24.0
npm: v6.14.11
@vue/cli: 4.5.13

二、问题描述

新建Vue项目的时候,如果选择hash模式的话,地址上都会带一个#号,本人嫌太丑,选择了history模式,到了部署项目的时候,刚好又需要多个项目部署在一起。部署完发现:① js、css文件找不到、② 页面报404、③ 页面报500。

三、问题解决

1、修改vue项目中的vue.config.js文件

a项目增加以下内容:

module.exports = {
	...	// 其他内容省略

    publicPath: process.env.NODE_ENV === 'production' ? '/a' : '/',    // production 正式环境,development 开发环境

};

b项目增加以下内容:

module.exports = {
	...	// 其他内容省略

    publicPath: process.env.NODE_ENV === 'production' ? '/b' : '/',    // production 正式环境,development 开发环境

};

2、修改Nginx的nginx.conf配置文件

    server {
        listen       12345;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;      # 只能有一个root,可以有多个alias
            index  index.html index.htm;
            #下面这一句是重点,意思就是将地址都导向index.html
            try_files $uri $uri/ /index.html;
        }
		
		location /a {    # a项目
			alias html/a;
			index index.html index.htm;
			#下面这一句是重点,意思就是将地址都导向index.html
			try_files $uri $uri/ /a/index.html;
		}
		
		location /b {    # b项目
			alias html/b;
			index index.html index.htm;
			#下面这一句是重点,意思就是将地址都导向index.html
			try_files $uri $uri/ /b/index.html;
		}



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

3、Nginx目录结构

在这里插入图片描述
好了,这样配置好后就可以解决以上所有的问题了。

在这里插入图片描述

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值