[Angular] Apache 서버로 Angular 앱을 배포했을때 404 에러가 날 경우

SPA(Single Page Application)을 Apache서버를 통해 서비스를 할 경우 주의해야 할 점이 있다.

루트 url을 제외한 url을 페이지를 새로고침하거나 브라우저에 직접 입력해서 접근하는 경우 404에러를 접하게 된다.

비단 Angular로 만들어진 앱 뿐만아니라 React나 Vue로 만들어진 앱도 마찬가지일 것이다. (HashLocation strategy를 사용할 경우는 예외)

그도 그럴것이 우리가 입력하는 url의 경우 Apache에 전달되게 되는데 Apache에는 해당 리소스들이 없기 때문이다. 해결 방법은 모든 url request를 index.html로 가게 만들어 주면 된다.

SPA가 있는 디렉토리에 .htaccess 파일을 만들어 다음과 같이 작성해 준다.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !/api
  RewriteRule . /index.html [L]
</IfModule>

그리고 Apache의 rewrite 모듈을 활성화 해주고 Apache설정에 다음과 같이 SPA디렉토리 경로에 대해 설정을 추가해 준다.

<Directory "/path-to-spa">
  AllowOverride All
</Directory>

자세한 내용은 아래 링크를 참고한다.

https://github.com/mgechev/angular-seed/wiki/Deploying-prod-build-to-Apache-2

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다