我在 APACHE 上托管了我的 ASP.NET Core 网站。问题是它在网址上显示端口,即 https://mywebsite.com:5001/ 是浏览器在网址上显示的内容。
KESTREL 上开放了 2 个端口。
"Kestrel": {
"Endpoints": {
"MyHttpEndpoint": {
"Url": "http://localhost:5000"
},
"MyHttpsEndpoint": {
"Url": "https://localhost:5001"
}
}
}
重定向中间件已添加到program.cs中。
app.UseHttpsRedirection();
应用程序运行正常,参见图片:
Apache 配置文件代码是:
<VirtualHost *:80>
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/
ProxyPassReverse / http://127.0.0.1:5000/
ServerName mywebsite.com
ServerAlias *.mywebsite.com
ErrorLog C:/xampp/apache/logs/error.log
#CustomLog C:/xampp/apache/logs/access.log
</VirtualHost>
<VirtualHost *:443>
Protocols h2 http/1.1
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/
ProxyPassReverse / http://127.0.0.1:5000/
ServerName mywebsite.com
ServerAlias *.mywebsite.com
ErrorLog C:/xampp/apache/logs/error.log
#CustomLog C:/xampp/apache/logs/access.log
SSLEngine on
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLHonorCipherOrder off
SSLCompression off
SSLSessionTickets on
SSLUseStapling off
SSLCertificateFile C:/xampp/htdocs/aspnetcore/server.crt
SSLCertificateKeyFile C:/xampp/htdocs/aspnetcore/server.key
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
</VirtualHost>
现在,当我在浏览器上打开网站网址 mywebsite.com 时。我看到它添加了端口 5001。见下图:
理想情况下,我期望浏览器网址上只是https://mywebsite.com,但不是我得到的。我引用的文档是MS docs。
出了点问题,我无法弄清楚。有什么帮助吗??
问题是你不应该使用
app.UseHttpsRedirection();
。如果我们去查看文档
我们可以找到
Note
Apps deployed in a reverse proxy configuration allow the proxy to handle
connection security (HTTPS). If the proxy also handles HTTPS redirection,
there's no need to use HTTPS Redirection Middleware. If the proxy server also
handles writing HSTS headers (for example, native HSTS support in IIS 10.0
(1709) or later), HSTS Middleware isn't required by the app. For more
information, see Opt-out of HTTPS/HSTS on project creation.
这正是您的情况,因为
Apache
是您的反向代理,因此最好通过 Apache
而不是您的 ASP.NET 应用程序来处理重定向,因为您的应用程序不知道您的 Apache
也在侦听端口443
,它只知道自己的https
端口是5001
,这就是为什么它被重定向到这个端口
要在您的情况下处理重定向
Apache
端口的配置80
应该类似于
<VirtualHost *:80>
ProxyPreserveHost On
ServerName mywebsite.com
ServerAlias *.mywebsite.com
Redirect permanent / https://mywebsite.com/
ErrorLog C:/xampp/apache/logs/error.log
#CustomLog C:/xampp/apache/logs/access.log
</VirtualHost>
当然,您可以在应用程序中保留重定向,但要使其正常工作,您需要使用
AddHttpsRedirection
此处的文档示例
它应该看起来像(基于示例):
builder.Services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = (int)HttpStatusCode.TemporaryRedirect;
options.HttpsPort = 443;
});
端口应该是
443
,因为它必须是 Apache
的端口,而不是您的全部,因为 Apache
会将所有请求转发到您的应用程序