Back-end/Spring Boot

Vue + SpringBoot ) url 직접 입력해서 이동 되도록 설정하는 방법

luana_eun 2025. 7. 16. 13:12
728x90

 

 

기본 적인 vue의 라우터는 history router 이다. 

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory()
});

 

 

이 라우터는 깔끔한 url을 제공하지만, 직접 주소창에 입력해서 들어갈 수는 없고 버튼을 통해서만 이동할 수 있다.

 

주소창에 직접 url을 입력해서 이동하는 방식을 사용하려면 Hash 모드 라우터를 사용해야한다. 

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
})

 

이 라우터는 url 중간에 #이 들어가서 /#/about 이런식의 형태가 된다. 

 

#은 숨김처리 할 수 있지만, 기본적으로 해시모드는 기록을 남기지 않기 때문에 뒤로가기가 기본 제공되지 않고, 

 

SEO(검색 엔진 최적화) 에 불리하여 구글에서 검색 시 노출되는데에 불리하다. 

 

 

따라서 나는 개발할 때는 불편하더라도 vue에 설정하지 않고 spring boot에 설정해서 

 

백엔드 실행 시에 url을 직접 입력해서 이동이 가능하도록 설정하려고 한다. 

 

 

 

Spring Boot에 포워딩 설정 방법!

1번과 2번중에 원하는 걸로 하면된다

 

 1. Fowarding 컨트롤러 생성 

package com.프로젝트명.패키지명;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SpaForwardController {

    @RequestMapping({"/{path:[^\\.]*}", "/**/{path:[^\\.]*}"})
    public String forward() {
        return "forward:/index.html";
    }
}

 

주소가 .의 주소들을 제외하고 Vue 라우터 경로만 html 파일로 보낸다는 의미다. 

 

/app.js, /style.css, /image/logo.png 같은 정적 파일 요청은 무시된다. 

 

 

 

 2. WebMvcConfigurer 설정하기 

 

요청한리소스가 없으면 /static/index.html 정적리소스를 리턴해주는 설정이다. 

 

config 패키지를 만들고 WebConfig 클래스를 생성한다.

package com.프로젝트명.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/{spring:[^\\.]+}")
                .setViewName("forward:/index.html");
                
        registry.addViewController("/**/{spring:[^\\.]+}")
                .setViewName("forward:/index.html");
    }
}

 

 

 

※ 혹시 스프링부트 Spring Boot 2.6 버전 이상이라면 정규식에 대한 허용 설정을 추가해야한다. 

application.properties에 코드 추가

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

 

 

 

 

잘 이동한다 😀

 

 

 

 

 

728x90