각도 루트의 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전체 Angular에 대하여JS 루트
앱 요청 시 문제가 발생함directive템플릿 파일이 누락되었습니다.경우에 따라서는 어플리케이션에서 여러 스크립트파일을 요구하게 되었습니다.index.html.
우리는 보내야 한다404대신 반응index.html파일이 존재하지 않는 경우.그래서 누락된 파일 요청을 식별하기 위해 간단한 regex 패턴을 추가합니다.
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]
/index.filename 앞에 .를 추가하고 https://example.com/subfolder과 같은 내 도메인에 해당 파일을 추가하면 정상적으로 작동합니다.
다음 링크를 확인해 주세요.https://stackoverflow.com/a/49455101/5899936 Create.htaccessroot 폴더에 파일을 저장하여.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>
julianpoemp.github.io/ngx-htaccess-generator/에는 훌륭한 "Angular generator"가 있습니다.
생성기는 오픈 소스입니다(소스 코드는 github.com/julianpoemp/ngx-htaccess-generator)에서 확인할 수 있습니다).
생성된.htaccess디폴트로는 다음과 같이 표시되며 정상적으로 동작합니다.
# Generated with ngx-htaccess-generator v1.2.0
# Check for updates: https://julianpoemp.github.io/ngx-htaccess-generator/
#
# Transparency notice: Some parts were extracted from
# Apache Server Configs v5.0.0 | MIT License
# https://github.com/h5bp/server-configs-apache
# Extracted parts are wrapped by "START Extract from ASC"
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirection of requests to index.html
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^.*$ - [NC,L]
# Redirect all non-file routes to index.html
RewriteRule ^(?!.*\.).*$ index.html [NC,L]
</IfModule>
Angular를 사용한 테스트 성공13.0.3.
다음 경우에 대비하여 다른 상세 htaccess 파일을 제공하겠습니다.
- baseUrl 및 기본 인덱스 파일을 고려합니다.
- 관리할 선행 슬래시를 삭제합니다.params
여기 htaccess가 있습니다.매우 가깝지만 보다 구체적인 것은 다음과 같습니다.
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]
좀 더 인 범위가 요..htaccess예를 들어 다음과 같이 설정합니다.
- HTTPS 프로토콜로 강제 적용(아래 참조).
- 역역
Authorizationheader header header header header header 。HTTP_AUTHORIZATION환경 변수입니다. - Cross-Origin Resource Sharing(CORS)
- 또, 특정의 포맷에 대해서 캐시를 무효로 했다(코멘트 아웃).
# If mod_rewrite is not present.
<IfModule !mod_rewrite.c>
FallbackResource /index.html
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Prefix for all rewritten routes ("index.html" gets "/index.html").
RewriteBase /
# Redirects to HTTPS protocol (once uncommented).
#
# RewriteCond %{HTTPS} !on
# RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
# Make sure Authorization HTTP header is available.
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Allows access to existing files or dirs.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# Prevents treating the main-script as a route.
RewriteRule ^index\.html$ - [L]
# Redirect anything else to main-script
RewriteRule ^(.*) index.html [NC,L]
</IfModule>
# Enable Cross-Origin Resource Sharing (CORS)
#
<IfModule mod_headers.c>
Header merge Vary Origin
# Allows any origin (just like "*", but works in more cases)
SetEnvIf Origin "^(http(s)?://[^/:]*(?::\d{1,5})?)?" REQUEST_ORIGIN=$1
Header always append Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "*"
Header always set Access-Control-Expose-Headers "*"
</IfModule>
# Disables Browser caching for production (edit pattern as you wish).
#
#<FilesMatch "\.(html|htm|js|json|css)$">
# # Ensures "Expires" header is not overridden by module.
# <IfModule mod_expires.c>
# ExpiresActive Off
# </IfModule>
# <IfModule mod_headers.c>
# FileETag None
# Header unset ETag
# Header unset Pragma
# Header unset Cache-Control
# Header unset Last-Modified
# Header set Pragma "no-cache"
# Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
# Header set Expires "Mon, 10 Apr 1972 00:00:00 GMT"
# </IfModule>
#</FilesMatch>
주의: 사용방법[L][L,R=301]후자의 경우 브라우저가 리다이렉트를 영구적으로 캐시하기 때문에(그리고 언젠가 해당 루트가 파일인 경우에도 리다이렉트됩니다).
angular는 AJAX 어플리케이션이기 때문에 html4에서는 구현할 수 없습니다..htaccess 파일에서 html5 모드를 활성화하기만 하면 됩니다.
angular.module('main', []).config(['$locationProvider', function($locationProvider) {
...
$locationProvider.html5Mode(true);
...
});
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 resource doesn't exist, use index.html
RewriteRule ^ /index.html
언급URL : https://stackoverflow.com/questions/22739455/htaccess-redirect-for-angular-routes
'source' 카테고리의 다른 글
| ajax가 사용할 수 있는 websocket/socket.io의 단점은 무엇입니까? (0) | 2023.02.15 |
|---|---|
| AWS: ID 풀 구성이 잘못되었습니다.이 풀에 대해 할당된 IAM 역할 확인 (0) | 2023.02.15 |
| AJAX 요청 시 Greasemonkey 스크립트를 실행합니다. (0) | 2023.02.15 |
| 여기서 'it()' 함수는 무엇을 하고 있습니까? (0) | 2023.02.15 |
| Postgres에서의 JSON과 JSONB의 차이점 (0) | 2023.02.15 |