【发布时间】:2021-09-13 05:12:49
【问题描述】:
我用 react nodejs 创建了一个小型 Web 应用程序。我托管在 IIS Web 服务器上。我想将非 www URL 重定向到 www 和 HTTP 到 HTTPS。我在web.config文件下面使用了重定向
<?xml version="1.0"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
<rule name="httptohttps" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
</rule>
<rule name="non-wwwtowww" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^example\.com$" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
上面的代码在登陆页面上可以正常工作,但对于其他页面 HTTPS 不起作用。我已经购买了 SSL 证书。
如果我直接打开 example.com/xyz 页面,那么打开的非安全页面意味着打开了http://example.com/xyz 页面。
如果我从 URL 中删除了 s 和 www 意味着 https://www.example.com/xyz 则不会执行路由。
我想将我的网络应用的所有页面路由到 HTTPS 和 www。
我在服务器端(node js)写了一些代码
//301 redirection http to https and non-www to www
const redirectionFilter = function (req, res, next) {
const theDate = new Date();
const receivedUrl = `${req.protocol}:\/\/${req.hostname}:${port}${req.url}`;
if (req.get('X-Forwarded-Proto') === 'http') {
const redirectTo = `https:\/\/${req.hostname}${req.url}`;
console.log(`${theDate} Redirecting ${receivedUrl} --> ${redirectTo}`);
res.redirect(301, redirectTo);
} else {
next();
}
};
/**
* Apply redirection filter to all requests
*/
app.get('/*', redirectionFilter);
app.use((req, res, next) => {
const host = req.header('host');
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, `${req.protocol}://www.${host}${req.url}`);
}
});
【问题讨论】: