IT Share you

Angular 경로에 대한 htaccess 리디렉션

shareyou 2020. 11. 29. 12:38
반응형

Angular 경로에 대한 htaccess 리디렉션


다음과 같은 여러 경로가있는 각도 응용 프로그램이 있습니다.

site.com/
site.com/page
site.com/page/4

angular의 html5 라우팅 모드를 사용하면 애플리케이션 내에서 링크를 클릭하면 올바르게 해결되지만 하드 새로 고침을 수행하면 404 오류가 발생합니다. 이 문제를 해결하기 위해 기본 htaccess 재 작성 구현을 시도했습니다.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteRule ^(.*)$ index.html [L]

이것은 각도 요청에 대해 작동하지만 스크립트를로드하거나 도메인 내에서 다음과 같이 ajax 호출을 시도 할 때 :

<script src="/app/programs/script.js"></script>

이 스크립트는로드되지 않습니다. 요청이 리디렉션되고 .htaccess가 요청을 다시 라우팅해야한다고 생각하므로 index.html 페이지를로드하려고합니다.이 파일이 존재하는지 모르고 리디렉션 대신 파일을로드해야합니다.

해결해야 할 실제 파일이없는 경우에만 htaccess가 요청을 index.html (보기 매개 변수 사용)로 리디렉션하도록 할 수 있습니까?


다음과 같은 스 니펫을 사용하십시오.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]

실제 리소스가있는 경우 해당 리소스로 건너 뛰고 index.html모든 AngularJS 경로 대해 건너 뜁니다 .


앱이 directive템플릿 파일을 요청 했지만 파일이없는 경우 문제가 있습니다 . 어떤 경우에는 앱이 index.html.

파일이 없으면 파일 404대신 응답 을 보내야 index.html합니다. 그래서 누락 된 파일 요청을 식별하기 위해 간단한 정규식 패턴을 추가합니다.

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested pattern is file and file doesn't exist, send 404
RewriteCond %{REQUEST_URI} ^(\/[a-z_\-\s0-9\.]+)+\.[a-zA-Z]{2,4}$
RewriteRule ^ - [L,R=404]

# otherwise use history router
RewriteRule ^ /index.html

가난한 사람의 해결책 (mod_rewrite를 사용하지 않음) :

ErrorDocument 404 /index.html

제 경우에는 아래와 같이 .htaccess 파일을 만듭니다.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) ./index.html [NC,L]

just added . before /index.html and add that file in my domain like https://example.com/subfolder and it's works fine


Check out this link : https://stackoverflow.com/a/49455101/5899936 Create .htaccess file in root folder and pase this in the .htaccess

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

I will provide another detailed htaccess file in case you need to :

  • Considerate the baseUrl and default index file
  • Remove the leading slash to manage :params

Here is my htaccess, very close, but more specific :

DirectoryIndex index.html
RewriteEngine on
RewriteBase /subDir
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]

참고URL : https://stackoverflow.com/questions/22739455/htaccess-redirect-for-angular-routes

반응형