В настоящее время у нас есть 2 версии нашего приложения Angular в службах Azure/App для поддержки интернализации.
Там же хостятся, но в разных папках / ru и /фр.. Наше дерево папок выглядит так
->
wwwroot/index.html
wwwroot/web.config
wwwroot/en/index.html
wwwroot/en/..
wwwroot/fr/index.html
wwwroot/fr/..
У нас есть правила перезаписи web.config, которые отлично работают. Смотри ниже :
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name = "Angular Routes fr" stopProcessing = "true">
<match url = "fr/.*" />
<conditions logicalGrouping = "MatchAll">
<add input = "{REQUEST_FILENAME}" matchType = "IsFile" negate = "true" />
<add input = "{REQUEST_FILENAME}" matchType = "IsDirectory" negate = "true" />
</conditions>
<action type = "Rewrite" url = "fr/" />
</rule>
<rule name = "Angular Routes en" stopProcessing = "true">
<match url = "en/.*" />
<conditions logicalGrouping = "MatchAll">
<add input = "{REQUEST_FILENAME}" matchType = "IsFile" negate = "true" />
<add input = "{REQUEST_FILENAME}" matchType = "IsDirectory" negate = "true" />
</conditions>
<action type = "Rewrite" url = "en/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Вот поворот; мы предоставляем корневой index.html на случай, если пользователь перейдет к www.app.com/* вместо www.app.com/en.
В этом случае запускается корневой index.html, и мы запускаем некоторый js-скрипт для перенаправления пользователя с помощью «window.location.href» в зависимости от языка локального хранилища.
По какой-то причине, когда мы запрашиваем URL-адрес из корня www.app.com
ссылку браузера и закешировал первую версию по этому URL-адресу.
Если мы запрашиваем URL-адрес с таким ресурсом www.app.com/en/*
браузер связывает ДРУГУЮ версию с этим путем, несмотря на тот же домен.
Проблема в том, что каждый раз, когда мы развертываем новую версию, обновляется только путь с любыми ресурсами, например: www.app.com/en/* или www.app.com/fr/*, но корневой URL-адрес www.app.com остается привязанным к старой версии и никогда не обновляется.
Если пользователь использует корневой URL-адрес, он будет перенаправлен на старую версию приложения, доступную только в памяти или на диске.
Обратите внимание, что www.app.com/en/* или www.app.com/fr/* работает отлично
На данный момент я не знаю, проблема в наших правилах перезаписи или в нашем перенаправлении сценария js.
Вот скрипт угловой сборки для /en -> ng build --output-path=dist/en --prod --base-href /en/ --i18n-locale en-CA --i18n-format=xlf
Вот наш корневой код index.html:
<html>
<head>
<meta http-equiv = "Cache-Control" content = "no-cache, no-store, must-revalidate" />
<meta http-equiv = "Pragma" content = "no-cache" />
<meta http-equiv = "Expires" content = "0" />
<script>
var edRedirectManager = (function () {
var _this = {};
_this.storageLocaleKey = "EDLocale";
_this.locale = "";
_this.init = function(){
_this.locale = (_this.getUserLanguage());
}
_this.redirect = function () {
var currentUrl = new URL(window.location.href);
var lgPrefix = _this.getUrlPrefixByLanguage();
currentUrl.pathname = _this.insert(currentUrl.pathname,lgPrefix,0);
window.location.href = currentUrl.href;
}
_this.getUserLanguage = function () {
try {
_this.locale = localStorage.getItem(storageLocaleKey);
} catch (error) {}
if (!this.locale) {
if (navigator.language.toUpperCase().indexOf("FR") !== -1)
this.locale = "fr-CA";
else
this.locale = "en-CA";
localStorage.setItem(this.storageLocaleKey, this.locale);
}
return _this.locale;
}
_this.getUrlPrefixByLanguage = function(){
var lgPrefix = "/fr";
if (this.locale.indexOf('en') !== -1){
lgPrefix = "/en";
}
return lgPrefix;
}
_this.insert = function (main_string, ins_string, pos) {
if (typeof (pos) == "undefined") {
pos = 0;
}
if (typeof (ins_string) == "undefined") {
ins_string = '';
}
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
return _this;
})();
</script>
</head>
<body>
<script>
// self executing function here
edRedirectManager.init();
edRedirectManager.redirect();
</script>
</body>
</html>
по умолчанию флажок «отключить кеш» установлен на вкладке сети. это может быть причиной того, что это сработало в прошлый раз
У меня та же проблема, но без интернационализации. Браузер загружается из кэша при выполнении запроса на рут (код ответа 200?), но по любому другому пути возвращает либо 200 (получает новую версию), либо 304 без изменений (кэшированная версия правильная). У меня такое чувство, что это может быть проблема Azure...





По какой-то причине страница "/ru/index.html" и/или "/fr/index.html" была кэширована при запуске из корня "/", что приводит к загрузке старого приложения main.js
Перенаправление сработало просто штрафом...
Я добавил тег этих настроек <location> в web.config со значением без кэша, и теперь эта проблема исчезла!
<configuration>
<location path = "en/index.html">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name = "Cache-Control" value = "no-cache" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
<location path = "fr/index.html">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name = "Cache-Control" value = "no-cache" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
<location path = "index.html">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name = "Cache-Control" value = "no-cache" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
<system.webServer>
<urlCompression doDynamicCompression = "true" />
<staticContent>
<mimeMap fileExtension = ".json" mimeType = "application/json" />
</staticContent>
<rewrite>
<rules>
<rule name = "Angular Routes fr" stopProcessing = "true">
<match url = "fr/.*" />
<conditions logicalGrouping = "MatchAll">
<add input = "{REQUEST_FILENAME}" matchType = "IsFile" negate = "true" />
<add input = "{REQUEST_FILENAME}" matchType = "IsDirectory" negate = "true" />
</conditions>
<action type = "Rewrite" url = "fr/index.html" />
</rule>
<rule name = "Angular Routes en" stopProcessing = "true">
<match url = "en/.*" />
<conditions logicalGrouping = "MatchAll">
<add input = "{REQUEST_FILENAME}" matchType = "IsFile" negate = "true" />
<add input = "{REQUEST_FILENAME}" matchType = "IsDirectory" negate = "true" />
</conditions>
<action type = "Rewrite" url = "en/index.html" />
</rule>
<rule name = "Angular Routes default" stopProcessing = "true">
<match url = ".*" />
<conditions logicalGrouping = "MatchAll">
<add input = "{REQUEST_FILENAME}" matchType = "IsFile" negate = "true" />
<add input = "{REQUEST_FILENAME}" matchType = "IsDirectory" negate = "true" />
</conditions>
<action type = "Rewrite" url = "/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Не могли бы вы приложить точные запросы и ответы для index.html и /en или /fr, которые выполняются при переходе к индексу? это легко сделать с помощью флажка «Сохранить журнал» на вкладке сети chrome devtools.