【发布时间】:2019-08-16 09:11:07
【问题描述】:
我有这个问题,我真的不知道如何处理它。首先,我在没有 SSL 的 localhost 上做了网站,一切都很好。现在我添加了 SSL,并将所有内容从 HTTP 迁移到 HTTPS。
但不知何故,即使我在 URL 中添加 https://,浏览器仍然会发出 Http 请求。
import { Injectable } from "@angular/core";
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
@Injectable()
export class EnsureHTTPSInterceptor implements HttpInterceptor
{
constructor()
{
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{
const parsedUrl = new URL(window.location.href);
const baseUrl = parsedUrl.origin; // this will print http://example.com or http://localhost:4200
const secureReq = request.clone
({
url: (baseUrl + request.url).replace('http://', 'https://')
});
console.log(secureReq);
// send the cloned, "secure" request to the next handler.
return next.handle(secureReq);
}
}
这是我的拦截器,它做得很好(我认为..)。 我认为这是 .htaccess 的问题,它强制 www、强制 https URL 和删除尾部斜杠。我让你看看.htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
DirectoryIndex index.php # This line does the trick
# Force SSL
# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Redirect Trailing Slashes If Not A Folder...
RewriteEngine on
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
# Force WWWW
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
另一件事是,即使我从 HTTP 请求中删除了尾部斜杠(在前端,如 /api/cart/products/ 到 -> /api/cart/products),应用程序仍然会添加它。
这就是 Chrome 的处理方式..
如果你想调试,你可以输入https://www.sarpilii.cf 然后在 Magazin -> 军事背包
如果您重新加载链接(例如:https://www.sarpilii.cf/produs/military-backpack),LARAVEL 将在 localStorage 中设置数据并且不会从 API 请求
【问题讨论】:
-
当我设置 SSL 时,我不需要拦截器,并认为这一切都是由服务器 https 重定向处理的。我可能错了。
-
@Nabel 你在构建应用程序时使用了 --ssl 吗?
-
啊我明白了我现在做了什么,我在我的生产文件中设置了一个用于 api 调用的基本 URL,即 https
标签: angular laravel redirect https